6条回答
  •  無奈伤痛
    2021-01-21 21:24

    You're setting the onclick attribute to the array of elements, not to each element individually like you need. Also, you're defining show after you've used it.

    var elts = document.getElementsByTagName('a');
    var show = function() { alert('hahahha'); }
    for (var i = elts.length - 1; i >= 0; --i) {
        elts[i].onclick = show;
    }
    

    It's more efficient to iterate backwards through the array than to test elts.length each time through. If you need to iterate forward, store the array length in a variable for better efficiency.

提交回复
热议问题