繁体   English   中英

如何使用 SetInterval 单击从 http 请求中获得的元素?

[英]How to click an element that we get from http request using SetInterval?

 window.addEventListener("load" , () => {
    setInterval(() => {
        let xhttp = new XMLHttpRequest();
        xhttp.open("GET", "./messagedUsers.php", true);
        xhttp.onload = () => {
            if(xhttp.readyState === XMLHttpRequest.DONE) {
                if(xhttp.status === 200) {
                    let data = xhttp.response;
                    sideActiveUsers.innerHTML = data;
                }
            }
        }
        xhttp.send();
    } , 500);
    messageInputContainer.focus();
})
let userInfo = document.querySelectorAll(".user-info");
userInfoClick(userInfo); // function that does operation using the nodeList userInfo

在上面的代码中,我想要做的是向 php 发送一个 HttpRequest 并从那里获得一个 div 容器作为响应。 作为回应,我得到了 div 容器。 我从那里得到的 div 有一个 class 名称“用户信息”。 我想单击它,然后将一些 css 应用到它包含的所有元素(因为响应中会有很多“用户信息”容器。)。 我无法弄清楚的是“用户信息”容器可以通过 css(不是 JS)应用样式。 但是,如果我尝试对 className 为“user-info”的节点使用一些 JS,则不会发生任何事情,因为 nodeList 似乎是空的。

而且我还尝试在 setInterval 中使用 querySelector 来获取“用户信息”。 但这使得 userInfoClick(userInfo) 之外的 function 采用未定义的 userInfo。

如果我同时使用 querySelector 和 function 来获取包含该 nodeList(userInfoClick) 的变量,我可以单击从 php 返回的元素。 但它的效果在每 500 毫秒后停止(因为 setInterval 设置为 500 毫秒)。

我希望能够单击从 php 返回的元素并单击其效果在每 500 毫秒后不会改变的元素(以及每 500 毫秒从 php 获取的元素)。

帮帮我,伙计们。

用户信息点击 function:

const userInfoClick = (userInfo) => {
    let userinfo = Array.from(userInfo);
    userinfo.forEach((el , ind) => {
        el.addEventListener("click" , () => {
            for(let i=0 ; i<userInfo.length ; i++)
                {
                    if(ind!==i)
                        {
                            userinfo[i].style.backgroundColor = "#dddddd";
                        }
                }
            el.style.backgroundColor = "#fff";
        })
    })   
}

您不能将事件处理程序绑定到尚不存在的元素。 querySelectorAll调用将返回一个空集合,因为对innerHTML的分配只会在将来发生。

在这种情况下,如果您有时间间隔,最好使用事件委托 这意味着您在 DOM 树的更高级别上侦听单击事件——在始终存在且不是动态创建的元素上。 在您的情况下,这可能是sideActiveUsers

所以改变你的代码如下:

删除这一行(因为它将返回一个无用的空集合):

let userInfo = document.querySelectorAll(".user-info");

并更改userInfoClick function,它应该只调用一次,没有任何 arguments:

function userInfoClick() {
    sideActiveUsers.addEventListener("click" , (e) => {
        const el = e.target;
        // We're only interested in user-info clicks:
        if (!el.classList.contains("user-info")) return;
        // Since we clicked on a user-info, the following will now have matches:
        for (const sibling of sideActiveUsers.querySelectorAll(".user-info")) {
            sibling.style.backgroundColor = "#dddddd";
        }
        el.style.backgroundColor = "#fff";
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM