[英]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.