gpt4 book ai didi

jquery - JavaScript/jQuery 在两个函数中使用一个变量的最佳解决方案?例子

转载 作者:行者123 更新时间:2023-12-01 06:50:20 25 4
gpt4 key购买 nike

我有点困惑。在 jQuery 中将一个变量用作全局变量的最佳方法是什么 - 只需使用它的两次单击功能?这是代码:

http://jsfiddle.net/DyqdA/

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com