javascript - 向 onclick 属性添加函数奇怪的行为

标签 javascript jquery html

我在将“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/

相关文章:

javascript - 在新窗口中打开 SSRS URL

javascript - 将页脚贴在底部(显示时)

html - 将所有导航项放入导航中,宽度相等且不换行

javascript - 使用 ng-click 为每次点击添加 HTML 代码

html - Div 没有正确包装链接

javascript - 使用javascript下载文件并显示内容

javascript - Sails.js 获得多对多关联计数

javascript - 如果 Windows 上的条件加载在 javascript 中不起作用

javascript - Webpack 和 imports-loader 错误 "Can' t 解决”

javascript - 当我单击链接时,我正在调用我的对话框,但对话框没有出现