开发者

attr is undefined

开发者 https://www.devze.com 2023-03-23 01:17 出处:网络
The following code this not work, because attr is undefined: $(\"#foo a[href]\").each(function() { this.attr(\"href\", \"www.google.com\");

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

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

But this code does:

$("#foo a[href]").each(function()开发者_Go百科
{
    this.href = "www.google.com";
});

Why??


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.com");
});


try .prop()

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


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

You need the $()


Because this isn't a jQuery object.

Try:

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


Did you mean this instead?

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

0

精彩评论

暂无评论...
验证码 换一张
取 消