我有一个问题,此代码有效,但是第一次点击不起作用,
当我第一次单击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');
});
}
});
答案 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);