javascript - 在目标中单击的对象是否有唯一 ID?
问题描述
使用以下代码,您可以看到创建每个椭圆时,名称始终保持不变。所以无论我点击哪个椭圆,我都会得到相同的名字。目标属性中是否存在某种唯一 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>
解决方案
尝试这个
<!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>
推荐阅读
- javascript - 如何在 ajax 调用时从 laravel 控制器函数返回视图?
- python - cx_Oracle:使用 Wallet 时如何连接到 Oracle?
- python - 替换数据框中的值仅与另一个数据框中匹配的值有关
- asp.net-core-3.1 - 如何获取当前服务健康检查的 URL?
- python - 使用变量而不是实际值会导致错误
- r - R for 循环问题:循环数据帧时“错误:$ 运算符对原子向量无效”
- javascript - 我应该避免在 Node js 上的每一个异步/等待中尝试捕获吗?
- artificial-intelligence - 简单策略游戏的 AI 技术
- c++ - Hackerrank-Count Triplets C++ 失败测试用例 #10 & #11
- python-3.x - (Python) 为什么运行“wut:2+2=5”行不会出现语法错误?