我在将“ExecuteDelete(index)”函数添加到 onclick 属性时遇到了一个奇怪的问题。这里的基本逻辑是,当用户单击“删除”时,它会触发“Remove(index)”函数,该函数会显示一个模态窗口,并向模态上的“确认删除”按钮添加一个 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");
}
感谢您的帮助。
-安德鲁
最佳答案
您应该使用jquery绑定(bind),而不是...onclick = ExecuteDelete(index);
$('#ExecuteDeleteButton')
.off('click')
.on('click', function() {
ExecuteDelete(index);
}
);
不要忘记 off()
来解除与重复使用的删除按钮的绑定(bind)!
关于javascript - 向 onclick 属性添加函数奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49389597/