簡體   English   中英

如何為多個事件處理程序使用變量?

[英]How to use a variable for multiple event handlers?

我想為一個事件處理程序設置一個變量,但從另一個事件處理程序中讀取它。

就像這樣:

$(document.body).on("click", ".notice", function() {
    var notice = 'You have just clicked this item.';
});
$('#save_comment').click(function() {
    alert(notice);
});

此代碼導致錯誤

未捕獲ReferenceError:通知未定義

var notice更改為notice ,否則它僅在定義它的函數內具有作用域。

嘗試這個

 var notice; $(document.body).on("click", ".notice", function() { notice = 'You have just clicked this item.'; }); $('#save_comment').click(function() { alert(notice); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="notice">notice</div> <div id="save_comment">save comment</div> 

單擊以保存評論將通知設置為未定義
點擊通知后賦予價值

然后使其成為全局:

$(document.body).on("click", ".notice", function() {
    notice = 'You have just clicked this item.';
});
$('#save_comment').click(function() {
    alert(notice);
});

根據您的情況,您可能可以執行以下操作以避免生成全局變量。

$(document.body).on("click", ".notice", function() {
    var notice = 'You have just clicked this item.';

  $('#save_comment').data('notice',notice);
});

$('#save_comment').click(function() {
    alert($(this).data('notice'));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM