开发者

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

开发者 https://www.devze.com 2023-04-09 16:50 出处:网络
$(\"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
$("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

精彩评论

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