attr is undefined
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"); ?
加载中,请稍侯......
精彩评论