【问题标题】:JQuery: TypeError: Object 0 has no method 'attr'JQuery:TypeError:对象0没有方法'attr'
【发布时间】:2011-07-27 16:01:53
【问题描述】:

这是我试图运行以“选择”页面中每个 .insite 元素的 href 属性的代码:

$('.insite').each(function(a) {
    a.attr('href');
});

不幸的是它失败并返回以下错误:

对象 0 没有方法 'attr'

我的做法有什么问题吗?

【问题讨论】:

    标签: jquery attributes css-selectors href


    【解决方案1】:

    不要使用“a”,而是使用“this”

    例如

    $('.insite').each(function(){
         $(this).attr('href');
    });
    

    【讨论】:

      【解决方案2】:

      试试这个

      $('.insite').each(function(i) {
          $(this).attr('href');
          // i is the current number of the element in collection
      });
      

      【讨论】:

        【解决方案3】:

        回调传递给.each()takes parameters (index, Element),但是你忘记了索引。试试:

        $('.insite').each(function(i, a) {
            alert(a.attr('href'));
        });
        

        或者只是:

        $('.insite').each(function() {
            alert($(this).attr('href'));
        });
        

        【讨论】:

          【解决方案4】:

          您的名为“a”的 var 只是一个迭代 var,因此您不能只键入 a.attr。

          如果你真的想使用“a”,你应该这样做:

          $('.insite').each(function(a) {
          var obj = $('.insite')[a];
          alert($(obj).attr("href"));
          });
          

          但我认为这样的东西真的更好:

          $('.insite').each(function() {
          $(this).attr("href");
          });
          

          【讨论】:

          • .each() 已经在回调的第二个参数中为您提供了元素引用。不需要另一个 DOM 遍历。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多