简体   繁体   中英

function called on page load while it must be called on onclick only

Here I want to call updateRecord("+n+") function on click Update button here res.data is the response from ajax. But when the page loads the updareRecord called itself. Following code is written in js file. and on click getting following error:

Uncaught SyntaxError: Unexpected identifier.

I request to mention exact point if you don't understand any point of question instead mark it negative.

$.map(res.data,function(n,i){
       if (n['type'] == 1)
            html += "<tr><td>" 
                 + n['locationName'] 
                 + "</td><td>" 
                 + n['categoryName'] 
                 + "</td><td>" 
                 + n['day'] 
                 + "</td><td>" 
                 + n['status'] 
                 + "</td><td><input type='button' onclick = '"+updateRecord(n)+ "' value='Update'/></td></tr>";  
 });

Because you are calling the function already when callback function is called. This happens right here on this line:

+ "</td><td><input type='button' onclick = '"+updateRecord(n)+ "' value='Update'/></td></tr>";

You call first updateRecord(n) and then append the return value to the text.

I would avoid adding events to DOM directly, but rather use something like this:

var button = $('<input type="button" value="Update" />');
button.click(function(event) {
   updateRecord(n);
}

The problem is, that you call the method:

html += "<input type='button' onclick = '"+updateRecord(n)+"' ...";
/* like this you execute the method directly, 
   like any other function call in javascript */

In case you'll write it like this:

html += "<input type='button' onclick = 'updateRecord("+n+")'...";
/* like this it is a string, and will be 
  interpreted by the javascript click eventhandler
  after adding the html string to the DOM */

It could work as expected, but the problem is, that you'll want to set an array/ object as parameter, which will cause an javascript error. To avoid that you could also do something like this:

$.map(res.data,function(n,i){
    if (n['type'] == 1) {
        html += "<tr><td>" + n['locationName'] + "</td><td>" + 
        n['categoryName'] + "</td><td>" + n['day'] + "</td><td>" + 
        n['status'] + "</td><td>" + 
        "<input class='update-button' data-value='"+ 
        /* since n is an associative array, will need 
           to stringify in a special way */
        JSON.stringify(n).replace(/'/g, "\\'")
        +"' type='button' value='Update'/></td></tr>";  
    }
});
/* bind an click event to all .update-button elements, 
whenever these elements will be appended to the DOM */
$(document).on('click','.update-button',function() {
    updateRecord($(this).data('value'));
});

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