简体   繁体   中英

display properties of an object with event target

I have written code that creates boxes based on user input in a form. I use a constructor function to give the boxes these values; name, color, id and number. I am supposed to make it so that when the user clicks on the box in the page, an alert box comes up that says what those values are for that individual box. I'm having trouble figuring out how to display most of those properties correctly.

Here is the function where I assign property values to the boxes, and also add them to the page:

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;           
    }                      
  }

Here is the function I have for displaying the info about the boxes:

function display(e) {
   var a = e.target.attributes;
   var b = e.target;
   console.log(b.name);     //shows "undefined"
   alert("id:" + "" + a[0].value); 
  }

My alert message works correctly, it shows an individual number for each box, based on the value of the counter. I don't understand why I can't get e.target to work to show name, color or number. I am a beginner, so any thoughts are much appreciated.

You need to use .getAttribute() for an attribute that you set.

function display(e) {
    var element = e.target || window.event.target;

    console.log(element.getAttribute('name'));   
}

If you'd like this to work in 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"));
}

Working in 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM