Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 向onclick属性添加函数_Javascript_Jquery_Html - Fatal编程技术网

Javascript 向onclick属性添加函数

Javascript 向onclick属性添加函数,javascript,jquery,html,Javascript,Jquery,Html,将ExecuteDeleteindex函数添加到onclick属性时遇到了一个奇怪的问题。这里的基本逻辑是,当用户单击“删除”时,它会触发Removeindex函数,该函数显示一个模式窗口,并向模式窗口上的“确认删除”按钮添加onclick属性。确认删除按钮onclick应该在模式窗口中单击确认删除按钮后执行 这将起作用,用户单击“确认删除”按钮后将显示警报 function Remove(index){ //set delete food modal message.

将ExecuteDeleteindex函数添加到onclick属性时遇到了一个奇怪的问题。这里的基本逻辑是,当用户单击“删除”时,它会触发Removeindex函数,该函数显示一个模式窗口,并向模式窗口上的“确认删除”按钮添加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");
        }
但是,当尝试为索引传入参数以便ExecuteElete知道要删除的内容时,调用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");
        }
谢谢你的帮助

-Andrew而不是…onclick=ExecuteDeleteindex;您应该像使用jquery绑定一样使用它

$('#ExecuteDeleteButton')
    .off('click')
    .on('click', function() { 
        ExecuteDelete(index);
    }
);
别忘了关闭从重复使用的删除按钮解除绑定

您正在对赋值执行函数

使用以下函数单击以绑定该事件:


因为您正在调用该函数,并且该函数返回的任何内容都将添加到事件侦听器中。你基本上是在做ExecuteDeleteindex;document.getElementById'ExecuteDeleteButton'。onclick=Undefinedy您必须分配函数引用,如中所述。您可以使用方法,以便Remove函数获得要处理的正确索引。
document.getElementById('ExecuteDeleteButton').addEventListener('click', 
    function() {
        ExecuteDelete(index);
    }
});