如何在 Javascript 中为 onclick PopUp 添加事件监听器?

考虑有一些超链接标签使 API 调用后端。


例子:


<a  href="/get/contact-info/" id="ember107" >Contact info </a>

后端 API 调用完成后,它将触发/打开该页面中的弹出窗口。


弹出数据:(示例一div数据)


<div id="ember"> <h1 id="pv-contact-info"> Contact Name</h1></div>

我的目标是从这个弹出窗口(标签上方)中提取数据。让我们说 h1 标签中的联系人姓名。


到目前为止我尝试过的:


let atag = document.getElementById("ember107");

atag.addEventListener('click', () => { 

    document.getElementById("pv-contact-info").innerText; // getting from popup h1 tag

});

atag.click(); // explicit click

我遇到的问题是Uncaught TypeError: Cannot read property 'click' of null执行这条语句时document.getElementById("pv-contact-info").innerText;


我知道问题是弹出内容未完全加载,这就是此代码 document.getElementById("pv-contact-info")返回 null 的原因。


我的问题是是否有监听器函数来检查 Popup 内容是否加载 完全或者我们可以用另一种方法来做到这一点。最好使用浏览器支持 /vanilla javascript 而不是库。


小唯快跑啊
浏览 51回答 2
2回答

婷婷同学_

您可以使用 MutationObserver 来监视页面上 DOM 的更改。如果您需要与旧版浏览器保持兼容,请使用单击事件来触发您自己的手动观察器。就像是:var interval_id = false;function lookForPopup(){    if(interval_id){        clearInterval(interval_id);    }else{        interval_id = setInterval(function(){            var popup = document.getElementById('some-id');            if(popup){                // do something                clearInterval(interval_id);            }        },1000);    }}

繁花不似锦

我如何使用MutationObserver解决此问题。MutationObserver has an ability to watch for changes being made to the DOM tree.&nbsp;I mention the code below how it fixed my issue/requirement.&nbsp;// selecting the href by id and triggering a click event.&nbsp;let hrefDoc = document.getElementById("ember");&nbsp;divDoc.click();let m = new MutationObserver(() => {&nbsp; let divDoc = document.getElementById("ember");&nbsp; &nbsp; new MutationObserver( () => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Finally Extracting the required data&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(document.getElementById("pv-contact-info").innerText);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }).observe(divDoc || document,observerOptions);&nbsp; });m.observe(hrefDoc,observerOptions);正如您在上面看到的,我添加了另一个子 MutationObserver 来观察 divDoc 元素。这是因为当 hrefDoc 点击事件时,父级 MutationObserver 回调会通过一些观察者选项被调用。但在这种情况下,我无法获取我的 <div id="ember"> 突变节点。这就是我添加另一个此语句let divDoc = document.getElementById("ember");并在子级中等待此 targetNode MutationObserver的原因。最后我从这个标签中提取了数据<h1 id="pv-contact-info">
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5