Javascript:使用 var 值作为 onclick window.open URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21874011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: Use var value as onclick window.open URL
提问by user3160260
How to use a var value and pass it to the window.open
url? I'm really no good at this, so the simpler the better. Thank you very much!
如何使用 var 值并将其传递给window.open
url?我真的不擅长这个,所以越简单越好。非常感谢你!
<script>
if (condition) {
var URL = "http://www.url.com";
} else {
var URL = "http://www.url2.com"
}
</script>
<div id="Banner" data-responsive="225h" onclick="window.open('URL','new_window');">
回答by okcoker
Notice there's no quotes around the URL
variable in window.open
. Also to be more concise, I've moved the var URL
portion out of the if/else logic.
请注意, 中的URL
变量周围没有引号window.open
。为了更简洁,我已经将这var URL
部分移出了 if/else 逻辑。
<script>
var URL;
if (condition) {
URL = "http://www.url.com";
} else {
URL = "http://www.url2.com"
}
</script>
<div id="Banner" data-responsive="225h" onclick="window.open(URL,'new_window');">
An even better solution would be to get rid of your inline click handlers altogether like so:
更好的解决方案是像这样完全摆脱内联点击处理程序:
<div id="Banner" data-responsive="225h"> ... </div>
<script>
function openWindow() {
var URL;
if (condition) {
URL = "http://www.url.com";
} else {
URL = "http://www.url2.com"
}
window.open(URL,'new_window');
}
var banner = document.getElementById('Banner');
banner.addEventListener('click', openWindow, false); //using addEventListener for brevity
</script>
回答by Rajesh
<script>
function a() {
if (condition) {
var URL = "http://www.url.com";
}
else {
var URL = "http://www.url2.com"
}
window.open(URL);
}
</script>
<div id="Banner" data-responsive="225h" onclick="a();">click me</div>
Alternative solution
替代方案
回答by Majed
If the point of your question is to have a clickable, formatted html area, You can use an anchor and have nested html elements inside it instead.I see this much cleaner.
如果您的问题的重点是有一个可点击的、格式化的 html 区域,您可以使用锚点并在其中嵌套 html 元素。我看到这更清晰。
<a href="http://www.google.com" target="_blank">
<p> I am an element inside an anchor</p>
<!-- you can put an image here instead -->
</a>
http://jsfiddle.net/CpXVB/