问题描述
我想在Jquery中设置一个全局变量,这样当我点击列表项时,被点击的列表项的id就成为变量的值。
我有以下代码,也在。
I want to set a global variable in Jquery so that when I click on a list item, the id of the clicked list item becomes the value of the variable.I have the below code which is also in this fiddle.
但是我的方式:在你点击列表项的时刻,值正确地放在console.log中。然后,当我点击演示div,变量被重置,
However the way I have it: At the moment when you click the list item,the value correctly gets put in the console.log.However afterthat when I click in the demo div,the variable is reset and is undefined.
当我点击演示时,如何获取id的值,当我点击列表项时是id的值?
How do I get the value of id when I click on demo,to be the value of id when I click on the list item?
例如:
当我点击aaa时,我点击演示框的值应该是id- 1
当我点击bbb时,点击演示框时的值应为id-2 >
when I click on bbb,the value when I click on the demo box should be id-2
<div id="demo"></div>
<ul>
<li id="id-1">aaa</li>
<li id="id-2">bbb</li>
</ul>
<script>
var id;
jQuery(document).on("click", "li", function (event) {
var id =jQuery(this).attr('id') || '';
console.log(id);
$( "#demo" ).show();
});
$(function() {
$("#demo").click(function(e) {
console.log(id);
});
});
</script>
<style>
#demo {
border: 1px solid;
display:none;
height: 100px;
width: 100px;
}
</style>
推荐答案
var id;
jQuery(document).on("click", "li", function (event) {
//should not not var here, using var here will declare the variable id as a local variable in the handler function scope
id = jQuery(this).attr('id') || '';
console.log(id);
$("#demo").show();
});
$(function () {
$("#demo").click(function (e) {
console.log(id);
});
});
这篇关于在Jquery中设置全局变量onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!