简体   繁体   English

javascript onclick方法仅适用一次

[英]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. 第一次单击Button时, func1很好用,但是再次单击时,它不起作用。

Even the alert('func1') does not work 即使是alert('func1')也不起作用

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 成功后尝试添加func1“ complete:function(){}”

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. 而不是删除单击并按如下所示在jquery中进行操作,这将为您的按钮注册事件。

$(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 使用Jquery取消附加onclick事件,然后附加它

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

repeat the above line in the Func1 itself Func1本身中重复以上行

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

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