首页 > 解决方案 > Javascript 使用 onclick 附加 div 元素需要双击

问题描述

我正在创建一个 div 元素并添加一个 onclick 以在屏幕上拖动元素。拖动本身按预期工作,但在我双击元素之前它不起作用。知道为什么我需要双击每个元素才能在屏幕上拖动它们/我可以做些什么来通过单击拖动元素?

我开始从 JS 内部动态构建它们之前,我不需要双击这些元素。

这是添加 onclick 的行:

node.onclick = function(){ 
   dragElement(document.getElementById(this.id)); 
}

这是整个函数:

function buildCards(){
    for(let x=0;x<4;x++){
        for(let i=0;i<13;i++){

            var individualCard = new Object();
            individualCard.value = i;

            if(x == 0){
                individualCard.type = 'club';
                individualCard.color = 'black';
            }else if(x == 1){
                individualCard.type = 'spade';
                individualCard.color = 'black';
            }else if(x == 2){
                individualCard.type = 'heart';
                individualCard.color = 'red';
            }else{
                individualCard.type = 'diamond';
                individualCard.color = 'red';
            }

            individualCard.id = individualCard.color+'-'+individualCard.value+'-'+individualCard.type;

            deckOfCards.push(individualCard);

            let node = document.createElement('div');
            node.className = 'cards';
            node.setAttribute("id", individualCard.id);
            node.onclick = function(){ 
                dragElement(document.getElementById(this.id)); 
            }
            node.style.background = 'url("cards/cards.png") '+-(i*72)+'px '+-(x*96)+'px';
            document.getElementById('gameBoard').appendChild(node);
        }
    }
}

根据 Goldie 的评论,我将 onclick 事件调整为事件侦听器。

document.getElementById("gameBoard").addEventListener("click",function(e) { 
if (e.target && e.target.matches("div.cards")) { 
      console.log("Anchor element clicked! "+e.target.id);
} });```

标签: javascripthtmlonclickdraggable

解决方案


我用 mousemove 替换了点击监听器,它工作得很好。

document.getElementById("gameBoard").addEventListener("mousemove",function(e) { 
    if (e.target && e.target.matches("div.cards")) { 
          console.log("Element id: "+e.target.id); 
    }});

推荐阅读