[英]Set Global Variable onclick in Jquery
我想在Jquery中設置一個全局變量,這樣當我單擊列表項時,單擊的列表項的id將成為變量的值。 我有下面的代碼也在這個小提琴 。
但是我擁有它的方式:當你單擊列表項時,正確地將值放入console.log.However然后當我點擊demo div時,變量被重置並且未定義。
當我點擊demo時,如何獲取id的值,當我點擊列表項時,它是id的值?
例如:
當我點擊aaa時,點擊演示框時的值應為id-1
當我點擊bbb時,單擊演示框時的值應為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);
});
});
你再次在循環中聲明id
。
var id;
jQuery(document).on("click", "li", function (event) {
id =jQuery(this).attr('id') || '';
console.log(id);
$( "#demo" ).show();
});
更改
var id =jQuery(this).attr('id') || ''; to
id =jQuery(this).attr('id') || ''; inside the loop.
這是因為你重新聲明了var id
var id; // GLOBAL
jQuery(document).on("click", "li", function (event) {
var id =jQuery(this).attr('id') || ''; // LOCAL TO THIS BLOCK
所以只需使用全局變量,
var id; // GLOBAL
jQuery(document).on("click", "li", function (event) {
id =jQuery(this).attr('id') || ''; // Use GLOBAL id here
演示http://jsfiddle.net/devmgs/LbZe6/1/
不要使用var inside,因為它會使它成為局部變量
var id;
jQuery(document).on("click", "li", function (event) {
id =jQuery(this).attr('id') || '';
console.log(id);
$( "#demo" ).show();
});
$(function() {
$("#demo").click(function(e) {
console.log(id);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.