第一次单击的窗口单击事件Javascript不起作用

时间:2019-03-20 17:02:12

标签: javascript dom-events

我有一个问题,此代码有效,但是第一次点击不起作用, 当我第一次单击window.open无效时,仅在第二次单击后有效。

let t = setInterval(function(){
        let x = document.createElement('p');
        x.className = 'text-style';
        x.innerHTML = games[cont];
        box.appendChild(x);
        if(cont >= games.length - 1){
            clearInterval(t);
        }
        cont++;
    },50);
    let gamesT = document.getElementsByClassName('text-style');
    window.addEventListener('click', function(){
        for(let i = 0; i < gamesT.length; i++){
            gamesT[i].addEventListener('click', function(){
                window.open('https://www.google.com/search?q=' + gamesT[i].innerHTML, '_blank');
                });
        }
    });

1 个答案:

答案 0 :(得分:2)

这是因为在创建元素时,它没有附加事件监听器。您可以通过创建函数并传递该点击来解决此问题。并在每个间隔中调用它

let gamesT = document.getElementsByClassName('text-style');
let t = setInterval(function(){
        let x = document.createElement('p');
        x.className = 'text-style';
        x.innerHTML = games[cont];
        box.appendChild(x);
        if(cont >= games.length - 1){
            clearInterval(t);
        }
        cont++;
        addListeners();
    },50);

function addListeners(){
    for(let i = 0; i < gamesT.length; i++){
        gamesT[i].onclick = function(){
              window.open('https://www.google.com/search?q=' + gamesT[i].innerHTML, '_blank');
         }
     }
}
window.addEventListener('click', addListeners);