简体   繁体   中英

Javascript onclick fires without click using it in loop

I'm using AJAX to get one of my database tables. 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?

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=\"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 :

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

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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