目标中单击的对象是否具有唯一的ID?

问题描述 投票:-1回答:1

使用以下代码,就像您看到的每个创建的椭圆形一样,名称始终保持不变。因此,无论单击哪个椭圆,我都会得到相同的名称。目标属性中是否埋有某种唯一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>
javascript html target
1个回答
0
投票

尝试一下

<!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>

© www.soinside.com 2019 - 2024. All rights reserved.