Jquery - 尝试在div动态创建时调用函数

时间:2017-10-11 15:00:25

标签: jquery

我正在尝试使其工作,以便在点击按钮时,创建 div ,并在创建<div id="login-history"> >函数运行对照该div的内容。

这就是我想要的:

1:点击按钮,它会加载登录历史记录,从而创建一个名为“登录历史记录”的新div。 2:当完全加载“登录历史记录”时,我希望运行该功能,检查每行是否与登录历史记录匹配。

这是我到目前为止所得到的,但由于某些原因它没有这样做:

//when accounts tab is clicked, run the checker function
$("#accountstab").on('click', function(){
    waitForElement("#loginhistory",checkerfunction());   
});

//function waitforElement that I got from here to wait on the element to load first as when you click accounts tab it may take 5-10 seconds to pull the login history

function waitForElement(elementPath, callBack){
    window.setTimeout(function(){
      if($(elementPath).length){
        callBack(elementPath, $(elementPath));
      }else{
        waitForElement(elementPath, callBack);
      }
    },500);
  }

function checkerfunction(){     
//variables of each Row in log history
var ip1 = $("#div.row.login-history").first();
var ip2 = $("#div.row.login-history").first().next();
var ip3 = $("#div.row.login-history").last().prev();
var ip4 = $("#div.row.login-history").last();
if ( $(ip1).text() == $(ip2).text() == $(ip3).text() == $(ip4).text()  ) {
//if they match, do nothing
}
else {
//add red banner alert if they don't match
    $("#accountstab").prepend("<div class='#alert warning'><span class='closebtn'>&times;</span><strong>Warning!</strong>Check the rows below for mismatch</div>");
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1 个答案:

答案 0 :(得分:0)

您正在调用回调函数,而不是传递它。所以改变这个:

waitForElement("#loginhistory",checkerfunction());  

使用:

waitForElement("#loginhistory",checkerfunction);  

&#13;
&#13;
//when accounts tab is clicked, run the checker function
$("#accountstab").on('click', function(){
    // Simulate load delay (for this snippet)
    setTimeout(function () { 
        $('<div>').attr('id', 'loginhistory').text('loaded').appendTo('body');
    }, 3000);
    waitForElement("#loginhistory", checkerfunction);   
});

function waitForElement(elementPath, callBack){
    window.setTimeout(function(){
        if($(elementPath).length){
            console.log('found! callback');
            callBack(elementPath, $(elementPath));
        }else{
            console.log('not yet found...');
            waitForElement(elementPath, callBack);
        }
    }, 500);
}

function checkerfunction(){     
    console.log('callback called');
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="accountstab">accountstab</button>
&#13;
&#13;
&#13;