JavaScript:getElementsByTagName()

时间:2016-05-11 13:34:38

标签: javascript jquery html dom

我可以为页面中的所有链接添加动画吗?

这里是代码

  var words = document.links;

  words.onmouseover = function() {
    words.classList.toggle("tada");
};

提前致谢。

2 个答案:

答案 0 :(得分:2)

getElementsByTagName('a')querySelectorAll('a')函数应按预期工作,分别返回HTMLCollectionNodeList,这两个函数都需要您迭代才能实际设置你的事件处理程序:

// Get your links
var links = document.getElementsByTagName('a');
// Iterate through them and set up your event handlers
for(var l = 0; l < links.length; l++){
      links[l].onmouseover = function () {
         this.classList.toggle("tadan");
      };
}

同样重要的是要注意getElementsByTagName()将返回&#34;直播&#34; HTMLCollection元素,而querySelectorAll()将返回&#34;非生存&#34; NodeList,可能会影响其中元素的使用方式。

答案 1 :(得分:0)

得到了loooopp

var link = document.getElementsByTagName( 'a' );

for(var i=link.length; i--;)
    link[i].onmouseover = function () {
          this.classList.toggle("tadan");
    };

你确实有jQuery标记,所以你可以

$('a').mouseover(function(){
    $(this).toggleClass('tadan');
});
相关问题