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>
JS implementation code:
function addPraiseNum() { var praiseObjs = document.getElementsByClassName('ml-praise'); 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('ding-num')[0]); } }
The implementation effect is as follows:
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!