Home > Web Front-end > JS Tutorial > body text

js implements the method of adding events to a tag (using closure loop)

高洛峰
Release: 2017-01-20 13:05:46
Original
1415 people have browsed it

The example of this article describes the method of adding events to the a tag in js. Share it with everyone for your reference, the details are as follows:

Explain with an example:

Achieve the effect: loop to add events to the a tag with ml-praise style class, and after clicking the a tag , the corresponding quantity increases by 1.

The Html structure is as follows:

<ul>
    <li><a href="javascript:;" class="ml-praise">数量:<span class="ding-num">100</span></a></li>
    <li><a href="javascript:;" class="ml-praise">数量:<span class="ding-num">200</span></a></li>
    <li><a href="javascript:;" class="ml-praise">数量:<span class="ding-num">300</span></a></li>
    <li><a href="javascript:;" class="ml-praise">数量:<span class="ding-num">400</span></a></li>
</ul>
Copy after login

JS implementation code:

function addPraiseNum() {
  var praiseObjs = document.getElementsByClassName(&#39;ml-praise&#39;);
  for (var i = 0; i < praiseObjs.length; i++) {
 var praiseObj = praiseObjs[i];
 praiseObj.onclick = (function (dingObj) {
   return function () {
 dingObj.innerHTML = parseInt(dingObj.innerHTML) + 1;
   };
 })(praiseObj.getElementsByClassName(&#39;ding-num&#39;)[0]);
  }
}
Copy after login

The implementation effect is as follows:

js implements the method of adding events to a tag (using closure loop)

I hope this article will be helpful to everyone in JavaScript programming.

For more js implementation methods of adding events to a tags (using closure loops), please pay attention to the PHP Chinese website for related articles!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template