简体   繁体   中英

javascript onclick method only works once

when I click Button the first time func1 works well, but when I click it again it doesn't work.

Even the alert('func1') does not work

What am I doing wrong?

 function func2(id) { $.ajax({ url: "url2", type: "POST", data: { id: id, }, cache: false, dataType: 'json', success: function (data) { if (data.status == 'success') { //do something } else { //do something } }, complete: function (XMLHttpRequest, status) { // } }); } function func1(id) { alert('func1'); var flag = false; $.ajax({ url: "url1", type: "POST", data: { id: id, }, cache: false, async: false, dataType: 'json', success: function (data) { if (data.status == 'false') { //do something flag = true; } }, }); if (flag) { func2(id); } } 
 <a id="xx_1" onclick="func1(1);">Button</a> <a id="xx_2" onclick="func1(2);">Button</a> .... <a id="xx_n" onclick="func1(n);">Button</a> 

Try adding in func1 "complete: function(){}" after success

function func1(id) {alert('func1');
    var flag = false;
    $.ajax({
        url : "url1",
        type : "POST",
        data:{
            id : id,
        },
       cache : false,
       async : false,
       dataType : 'json',
       success : function(data) {
            if(data.status == 'false') {
                //do something
                flag = true;
            } 
       },
       complete: function(){}
    });

instead of that remove the on click and do it in jquery as follows, this will register the event for your button.

$(document).on('click', '#YOUR_BTN_ID', function({
    var flag = false;
    $.ajax({
        url : "url1",
        type : "POST",
        data:{
            id : id,
        },
       cache : false,
       async : false,
       dataType : 'json',
       success : function(data) {
            if(data.status == 'false') {
                //do something
                flag = true;
            } 
       },
       complete: function(){}
    })});

Use Jquery to unAttach the onclick event then attach it

$(document).off.on('click', 'ButtonId', func1(1));

repeat the above line in the Func1 itself

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