模拟动态添加的div上的点击不存在于DOM中

时间:2018-02-09 15:25:42

标签: javascript jquery html ajax dom

据我所知,ajax回调会在我的html上为html添加一个新的div。我可以在html中看到这个元素添加但是由于某种原因我无法通过DOM访问它。我尝试从控制台中调用chrome和js bookmarklet 元素已经可见/添加到html中。我不确定为什么DOM没有提起它,但我认为这是另一个问题......

这是div:

<div class="recaptcha-checkbox-checkmark" role="presentation"></div>

我使用下面的内容来获取对它的引用但是90%的时间它返回null(偶尔,它实际上会返回一个引用,但老实说我不知道​​/理解为什么):

document.querySelector(".recaptcha-checkbox-checkmark");

我一直在关注different ways to bind to this new div所以我可以在它出现在html / dom中之后执行点击,但我无法将它们放在一起,因为它似乎可以绑定到click事件,但您无法绑定到shown事件:/

所以这就是我目前所拥有的,但它并不像(我猜)那样基于click事件并且我实际上没有点击它?

var host = document.querySelector("head");
if(host){

    var importJquery = function(){
        var jquery = document.createElement('script');
        jquery.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js")
        host.appendChild(jquery);
    }

    importJquery();

    var bindToCaptcha = function(){
        var script = document.createElement("script");
        script.innerHTML = '$(document).on("click", ".recaptcha-checkbox-checkmark", function(e) {alert("clicked: %o",  this);});';
        host.appendChild(script);
    }

    bindToCaptcha();
}

所以,为了清楚起见,我想确定这个div在html中显示的那一刻并执行点击它但不能,因为我错过了对它的引用。

我正在考虑在一个间隔运行一个循环,检查div是否存在但是我宁愿远离那种方法(而且我也不确定这会起作用,因为DOM似乎总是不会返回参考这个div)。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

我无法获得引用,因为我之后的元素位于iframe中。我觉得这个问题会在第一时间被我提到iframe的其他人立即回答,但我是新手,所以在我进一步挖掘之前我甚至都没有意识到这一点。

答案 1 :(得分:0)

您可以使用MutationObserver API来检测将子项添加到父元素的时间:

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

取自https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#Example_usage

的示例