最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - attr is undefined - Stack Overflow

programmeradmin5浏览0评论

The following code this not work, because attr is undefined:

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

But this code does:

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

Why??

The following code this not work, because attr is undefined:

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

But this code does:

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

Why??

Share Improve this question asked Jul 27, 2011 at 13:26 MattMatt 2,6441 gold badge16 silver badges19 bronze badges 1
  • Fyi, a link to www.google. will not do what you want. You need http:// in front of it. Unless you have a file named www.google. in the same folder as your html file of course ;) – ThiefMaster Commented Mar 3, 2012 at 20:52
Add a ment  | 

7 Answers 7

Reset to default 10

You need to wrap this ... $(this)

attr is a method of a jQuery object, href is a property of an element node

The this reference in your function is a reference to a DOM element. The reference is not a jQuery object.

Because this inside an each refers to the DOM element itself rather than the jQuery version of it, and the attr method is only defined on the jQuery object.

So, to use the attr method you need to wrap the DOM element in a jQuery object:

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

try .prop()

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

You need the $()

Because this isn't a jQuery object.

Try:

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

Did you mean this instead?

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

发布评论

评论列表(0)

  1. 暂无评论