$("a[href*='http://www.google.com开发者_开发百科']").attr('id','newId');
Can only reference it by href
.
Yes, that's the correct way to add an id
attribute to an element that doesn't already have one.
However you should ensure that there's only one matching element, as it's incorrect to have two elements with the same ID on a page, e.g.:
$("a[href*='http://www.google.com']").first().attr('id', 'newId');
This would, of course, still leave you with the problem of what to do with the remaining matching elements, if any. A possible solution would be:
$("a[href*='http://www.google.com']").attr('id', function(index, attr) {
return 'newId_' + index;
});
which will assign the elements the IDs newId_0
, newId_1
, etc.
精彩评论