【发布时间】:2018-08-29 14:02:33
【问题描述】:
我在将“ExecuteDelete(index)”函数添加到 onclick 属性时遇到了一个奇怪的问题。这里的基本逻辑是,当用户单击删除时,它会触发 Remove(index) 函数,该函数显示一个模态窗口,并在模态上的 Confirm Delete 按钮上添加一个 onclick 属性。确认删除按钮 onclick 应该在模态窗口中单击确认删除按钮后执行。
这将起作用,并且在用户单击确认删除按钮后将显示警报...
function Remove(index){
//set delete food modal message.
$("#DeleteFoodMessage").text("Are you sure you want to delete " + $("#FoodName-" + index).val());
//show modal.
$("#ConfirmDelete").modal();
//add onclick= event to the modal to delete the element at 'index'.
document.getElementById('ExecuteDeleteButton').onclick = ExecuteDelete;
}
function ExecuteDelete(index){
alert("This works");
}
但是,当尝试为索引传递参数时,以便 ExecuteDelete() 知道将要删除的内容,当调用 Remove() 函数时会调用警报。
function Remove(index){
//set delete food modal message.
$("#DeleteFoodMessage").text("Are you sure you want to delete " + $("#FoodName-" + index).val());
//show modal.
$("#ConfirmDelete").modal();
//add onclick= event to the modal to delete the element at 'index'.
document.getElementById('ExecuteDeleteButton').onclick = ExecuteDelete(index);
}
function ExecuteDelete(index){
alert("This does not work");
}
感谢您的帮助。
-安德鲁
【问题讨论】:
-
因为您正在调用该函数,并且该函数返回的任何内容都将添加到事件侦听器中。你基本上是在做
ExecuteDelete(index); document.getElementById('ExecuteDeleteButton').onclick = undefined -
您必须按照the documentation 中的说明分配函数引用。您可以使用Function.prototype.bind 方法,以便Remove 函数获取正确的索引来处理。
标签: javascript jquery html