【问题标题】:attr is undefinedattr 未定义
【发布时间】:2011-07-27 13:26:21
【问题描述】:

以下代码不起作用,因为 attr 未定义:

$("#foo a[href]").each(function()
{
    this.attr("href", "www.google.com");
});

但是这段代码可以:

$("#foo a[href]").each(function()
{
    this.href = "www.google.com";
});

为什么??

【问题讨论】:

  • 仅供参考,www.google.com 的链接不会满足您的要求。你需要 http:// 在它前面。除非您在与您的 html 文件相同的文件夹中有一个名为 www.google.com 的文件;)

标签: javascript jquery attr


【解决方案1】:

你需要包装this ... $(this)

attr是jQuery对象的方法,href是元素节点的属性

【讨论】:

    【解决方案2】:

    函数中的 this 引用是对 DOM 元素的引用。引用不是一个 jQuery 对象。

    【讨论】:

    • 顺便说一句,我一直想知道为什么它没有实现为默认包装。因为在 90% 的情况下人们会使用 $(this),而且相对而言很少需要 DOM 元素本身。
    • @shabuc 我经常将它用于 this.id、this.href 等。输入更少,最终结果相同,这是我在 js 库之前使用的方式。跨度>
    【解决方案3】:

    因为each里面的this指的是DOM元素本身而不是它的jQuery版本,而attr方法只定义在jQuery对象上。

    因此,要使用 attr 方法,您需要将 DOM 元素包装在 jQuery 对象中:

    $("#foo a[href]").each(function()
    {
        $(this).attr("href", "www.google.com");
    });
    

    【讨论】:

      【解决方案4】:

      试试 .prop()

      this.prop("href", "www.google.com");
      

      【讨论】:

        【解决方案5】:
        $("#foo a[href]").each(function()
        {
            $(this).attr("href", "www.google.com");
        });
        

        你需要 $()

        【讨论】:

          【解决方案6】:

          因为this 不是 jQuery 对象。

          试试:

          $("#foo a[href]").each(function() {
              $(this).attr("href", "www.google.com");
          });
          

          【讨论】:

            【解决方案7】:

            你的意思是这个吗?

            $(this).attr("href","www.google.com");?

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2016-05-22
              • 1970-01-01
              • 1970-01-01
              • 2014-01-19
              • 1970-01-01
              • 2011-08-02
              • 2015-09-06
              • 1970-01-01
              相关资源
              最近更新 更多