简体   繁体   中英

javascript triggering event when p element is clicked

I am writing a program in raw javascript. When a <p> element is clicked I wish this to trigger a function which adds the price of the element to the total. Please see my code below.

JS

function loadJSONDoc()
{
  var answer;
  var xmlhttp;
  xmlhttp=new XMLHttpRequest();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    answer = JSON.parse(xmlhttp.responseText)
    var items = answer[0].prices[0];

    for(var index in items) {

      var node = document.getElementById("orderList");
      var p = document.createElement('p');
      var price = items[index];
      p.setAttribute("class", price)
      var textnode = document.createTextNode(index + " price = " + price);
      p.appendChild(textnode);
      node.appendChild(p);
      };
    }

var total = 0;
var update = document.getElementsByTagName("p");
update.onclick = function(){
  ///code here to update total based on element id
}

After the JSON object has been returned and my html page has been updated it looks like this:

HTML

  <!DOCTYPE html>
    <html>
     <head>
      <meta charset="UTF-8">
     </head>
     <body>
      <ul id="orderList">
         <p class="4.75">Cafe Latte price = 4.75</p>
         <p class="4.75">Flat White price = 4.75</p>
         <p class="3.85">Cappucinoprice = 3.85</p>
     </ul>
     <script src="js/getData.js"></script>
     </body>
    </html>

I am able to target one <p> element by using the following code, however I am looking for a solution whereby my function will trigger if I click on ANY <p> element, which will in turn update the total based on the value of such <p> element's class. I hope this makes sense.

var update = document.getElementsByTagName("p")[0];
    update.onclick = function(){
     ///code here to update total based on element id
    }

Thanks, Paul

You will need to bind each item in document.getElementsByTagName("p") . You are only doing it for the first one. For example:

var update = document.getElementsByTagName("p");
for( var i = 0; i < update.length; ++i ) {
    update[i].onclick = function() { 
       //code here to update total based on element id
    }
}

Note: You can access the value of the <p> elements class by doing this.className inside the onclick function.

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