我有点困惑。在 jQuery 中将一个变量用作全局变量的最佳方法是什么 - 只需使用它的两次单击功能?这是代码:
HTML:
<div id = "div1">DIV # 1</div>
<div id = "div2">DIV # 2</div>
<input type = "button" value = "Click to see whick div you've chosen."/>
<h1></h1>
jQuery:
$(document).ready(function() {
var answer;
$("#div1").click(function(event) {
window.answer = "FIRST";
});
$("div2").click(function(event) {
window.answer = "SECOND";
});
$("button").click(function() {
$("h1").html(window.answer);
});
})(jQuery);
CSS:
#div1 {
background-color: red;
height: 50px;
}
#div2 {
background-color: blue;
height: 50px;
}
我需要将文本保存到答案变量中。 提前致谢。
最佳答案
只需删除 window.
因为这个变量不是全局的。它可以在您尝试使用它的上下文中访问:
$(document).ready(function() {
var answer;
$("#div1").click(function(event) {
answer = "FIRST";
});
$("#div2").click(function(event) {
answer = "SECOND";
});
$("input").click(function() {
$("h1").html(answer);
});
});
编辑:然后删除 (jQuery)
在最后。
编辑2:另外,div2
应该是#div2
而你没有button
在你的html中,你有一个 input
类型 button
.
关于jquery - JavaScript/jQuery 在两个函数中使用一个变量的最佳解决方案?例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15950741/