首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jquery -在div动态创建时尝试调用函数

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

Stack Overflow用户
提问于 2017-10-11 15:00:25
回答 1查看 147关注 0票数 0

我正在尝试实现这个功能,以便当单击按钮时,创建div,当创建<div id="login-history">时,针对该div的内容运行函数。

,我想要的是:

1:单击按钮并加载登录历史记录,从而创建一个具有id登录历史记录的新div。2:当“登录历史记录”完全加载时,我希望运行该函数,该函数将检查每一行是否与Login History中的每一行匹配。

这是我到目前为止所得到的,但它并不是出于某种原因而这么做:

代码语言:javascript
复制
//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>");
    }
}
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-11 15:08:20

您正在调用回调函数,而不是传递它。因此,改变这一点:

代码语言:javascript
复制
waitForElement("#loginhistory",checkerfunction());  

通过以下方式:

代码语言:javascript
复制
waitForElement("#loginhistory",checkerfunction);  

代码语言:javascript
复制
//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');
}
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="accountstab">accountstab</button>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46691588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档