据我了解,ajax 回调会在我的 html 中添加一个新的 div
。我可以看到这个元素添加到 html 中,但是由于某种原因我无法通过 DOM 访问它。我尝试从 chrome 控制台和 js 书签在元素已经可见/添加到 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 中后对其执行单击,但我无法将其组合在一起,因为似乎您可以绑定(bind)到 click
事件,但无法绑定(bind)到类似的事件显示
事件:/
这就是我目前拥有的,但它不起作用,因为(我猜)它是基于 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)。
非常感谢任何帮助。
最佳答案
您可以使用 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
关于javascript - 模拟点击动态添加的 DOM 中不存在的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48709029/