addID in jQuery?

后端 未结 4 641
日久生厌
日久生厌 2020-12-01 01:02

Is there any method available to add IDs like there is for adding a class - addClass()?

4条回答
  •  离开以前
    2020-12-01 01:50

    I've used something like this before which addresses @scunliffes concern. It finds all instances of items with a class of (in this case .button), and assigns an ID and appends its index to the id name:

    $(".button").attr('id', function (index) {
    	return "button-" + index;
    });

    So let's say you have 3 items with the class name of .button on a page. The result would be adding a unique ID to all of them (in addition to their class of "button").

    In this case, #button-0, #button-1, #button-2, respectively. This can come in very handy. Simply replace ".button" in the first line with whatever class you want to target, and replace "button" in the return statement with whatever you'd like your unique ID to be. Hope this helps!

提交回复
热议问题