简体   繁体   English

单击p元素时的javascript触发事件

[英]javascript triggering event when p element is clicked

I am writing a program in raw javascript. 我正在用原始JavaScript编写程序。 When a <p> element is clicked I wish this to trigger a function which adds the price of the element to the total. 单击<p>元素时,我希望它触发一个函数,该函数将元素的价格加到总计中。 Please see my code below. 请在下面查看我的代码。

JS 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: 在返回JSON对象并且更新了我的html页面之后,它看起来像这样:

HTML 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. 我可以使用以下代码定位一个<p>元素,但是我正在寻找一种解决方案,如果我单击ANY <p>元素,则函数将触发,这将反过来基于的值更新总数这样的<p>元素的类。 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") . 您将需要绑定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. 注意:您可以通过在onclick函数中执行this.className来访问<p>元素类的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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