【问题标题】:Is there a unique ID for objects clicked within target?在目标中单击的对象是否有唯一 ID?
【发布时间】:2020-02-17 21:27:06
【问题描述】:

使用以下代码,您可以看到创建每个椭圆时,名称始终保持不变。 所以无论我点击哪个椭圆,我都会得到相同的名字。目标属性中是否存在某种唯一 ID?

<!DOCTYPE html>
<html lang="en">
<input type="button" onClick="doit()" value="Do it">

<script>
function doit() {
    drawOval(160,80,50);
    myOval = document.getElementById("newdiv");
} 

function drawOval(width, height, radius) {
    if (document.createElement) {

       newdiv=document.createElement("div");
       newdiv.style.width = width+"px";
       newdiv.style.height = height+"px";
       newdiv.style.backgroundColor = 'red';
       newdiv.style.visibility = 'visible';
       newdiv.style.borderRadius = radius+"%"

       newdiv.id = 'newdiv';// + i;
       document.body.appendChild(newdiv);
    }
}

document.onclick = function(f){
    alert(f.target.id)
}
</script>

</html>

【问题讨论】:

  • 好吧,newdiv.id = 'newdiv'; 你的 id 是一样的
  • 我看不出没有 body 的 html 文档如何工作
  • @MisterJojo 正文是optional。另请参阅here: "如果元素为空,或者如果 body 元素内的第一件事不是 ASCII 空格或注释,则可以省略 body 元素的开始标记,除非 body 元素内的第一件事是元、链接、脚本、样式或模板元素。”

标签: javascript html target


【解决方案1】:

试试这个

<!DOCTYPE html>
<html lang="en">
<input type="button" onClick="doit()" value="Do it">

<script>
    var id = 1;
function doit() {
    drawOval(160,80,50);
    myOval = document.getElementById("newdiv");
} 

function drawOval(width, height, radius) {
    if (document.createElement) {

       newdiv=document.createElement("div");
       newdiv.style.width = width+"px";
       newdiv.style.height = height+"px";
       newdiv.style.backgroundColor = 'red';
       newdiv.style.visibility = 'visible';
       newdiv.style.borderRadius = radius+"%"

       newdiv.id = 'newdiv' + id;// + i;
        id++;
       document.body.appendChild(newdiv);
    }
}

document.onclick = function(f){
    alert(f.target.id)
}
</script>

</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-16
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多