在javascript中将变量从一个事件处理程序传递到另一个事件处理程序
我在视图中有以下js代码:在javascript中将变量从一个事件处理程序传递到另一个事件处理程序,javascript,jquery,Javascript,Jquery,我在视图中有以下js代码: //here I initialize two variables to temporaly store values var id = 0; var tr = ""; $(document).on("click", ".deleteItem", function(e) { $('#deleteItemConfirmationModal .modal-body').html("Please confirm deleting this item");
//here I initialize two variables to temporaly store values
var id = 0;
var tr = "";
$(document).on("click", ".deleteItem", function(e) {
$('#deleteItemConfirmationModal .modal-body').html("Please confirm deleting this item");
$('#deleteItemConfirmationModal').modal('show');
// here I need two parameters (id and tr) to pass them into another function, so I save them into variables
id = $(this).data('id');
tr = $(this).closest("tr");
});
然后,如果用户确认应该删除该项目。其代码如下所示:
$('#deleteItemConfirmationModal .modal-footer').on('click', function(event) {
var $button = $(event.target);
buttonId = $button[0].id;
if (buttonId === 'yesBtn') {
$.ajax({
url: '@Url.Action("Delete")',
type: 'POST',
data: { itemId: id }, // use first variable
success: function (data) {
if (data.IsOK) {
tr.remove(); // use second variable
}
}
});
}
});
代码运行良好。但我不认为像这样传递变量是一种好的做法
我可以使用这种方法吗?或者有另一种方法不使用全局变量吗?您可以将变量附加到模式。差不多
$('#deleteItemConfirmationModal').data('id', id);
$('#deleteItemConfirmationModal').data('tr', tr);
然后,当您想要使用它们时,只需将值取回即可
var id = $('#deleteItemConfirmationModal').data('id');
var tr = $('#deleteItemConfirmationModal').data('tr');
这应该是安全的,因为这些值在模态显示时应用于模态。实际上,您正在将它们附加到
文档中,我可以理解为什么您会有点不安。您可以触发自定义事件并将数据传递给它们。
下面是一个简单的例子:
$('#root')。在('click','one','two',函数(e){
$('#root').trigger('myEvent',{param:e.target.id})
});
$('#root')。关于('myEvent',函数(e,数据){
console.log(data.param);
});代码>
一
二
那么您关心全局变量?