[英]display properties of an object with event target
我已经编写了基于表单中的用户输入创建框的代码。 我使用构造函数为这些框赋予这些值。 名称,颜色,ID和编号。 我应该这样做,以便当用户单击页面中的框时,会出现一个警告框,其中指出了该单独框的值。 我在弄清楚如何正确显示大多数这些属性时遇到了麻烦。
这是我将属性值分配给框并将其添加到页面的函数:
function addBox(newbox) {
for (var i = 0; i < newbox.number; i++) {
counter++;
var scene = document.getElementById("scene");
var div = document.createElement("div");
div.setAttribute("id", counter);
div.className += " " + "box";
div.innerHTML += newbox.name;
div.style.backgroundColor = newbox.color;
var x = Math.floor(Math.random() * (scene.offsetWidth-101));
var y = Math.floor(Math.random() * (scene.offsetHeight-101));
div.style.left = x + "px";
div.style.top = y + "px";
scene.appendChild(div);
div.onclick = display;
}
}
这是我用于显示有关框的信息的功能:
function display(e) {
var a = e.target.attributes;
var b = e.target;
console.log(b.name); //shows "undefined"
alert("id:" + "" + a[0].value);
}
我的警报消息可以正常工作,它会根据计数器的值为每个框显示一个单独的数字。 我不明白为什么我不能让e.target来显示名称,颜色或数字。 我是一个初学者,因此任何想法都很感激。
您需要对设置的属性使用.getAttribute()
。
function display(e) {
var element = e.target || window.event.target;
console.log(element.getAttribute('name'));
}
如果您希望在IE中使用此功能:
function display(e) {
b = e ? e.target : window.event.srcElement,
ret=[];
console.log(b.getAttribute("name"));
// all attributes:
for(att in b){
ret.push(att+b[att]);
}
alert(ret.join("\n"));
}
在IE中工作
$(document).click(function (e) { var element = e.target || window.event.target; console.log(element.getAttribute('id')+":"+element.getAttribute('name')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.