简体   繁体   English

Javascript onclick 触发而无需单击在循环中使用它

[英]Javascript onclick fires without click using it in loop

I'm using AJAX to get one of my database tables.我正在使用 AJAX 来获取我的数据库表之一。 I'm trying to improve it by making an update table function after the button is pressed.我正在尝试通过在按下按钮后创建更新表功能来改进它。

success: function(result) {
    for( var i = 0; i < result.length; i++ ) {
        document.getElementById('tableT').innerHTML +=
            "<tr>" +
                "<td>"+result[i]['id']+"</td>" +
                "<td>"+result[i]['terminalId']+"</td>" +
                "<td>"+result[i]['departmentId']+"</td>" +
                "<td>"+result[i]['profileId']+"</td>" +
                "<td>"+result[i]['created']+"</td>" +
                "<td>"+result[i]['modified']+"</td>"+
                "<td>"+"<div style='margin-bottom:10px; text-align: center;'>"+
                "<a class='btn btn-info edit-btn' data-toggle='modal' onclick='"+updApplication(result[i]['id'])+"' data-target='#myModal-44' title='Edit'><i class='fa fa-edit'></i></a>"+
                    "</div>"+"</td>"+
            "</tr>";

    }
},

Why do I get alerts with all my ids without even pressing a button?为什么我什至不按按钮就收到所有 ID 的警报?

function updApplication(id){
    alert(id);
};

You get alerts because you are actually calling the function when building your markup.您会收到警报,因为您实际上是在构建标记时调用该函数。

Try defining the onclick with your function as a string.尝试使用您的函数将onclick定义为字符串。

"onclick=\"updApplication(" + result[i]['id'] + ")\"..."

You have a problem in quotes, now you're calling updApplication() function in every loop iteration, your code should be like :你在引号中有问题,现在你在每次循环迭代中调用updApplication()函数,你的代码应该是这样的:

..data-toggle='modal' onclick='updApplication("+result[i]['id']+")' data-target='#myModa..

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM