开发者

Is this the correct way to set an id for an element that doesn't have an id yet in jQuery?

$("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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜