wrapAll() only working on the first element?

2019-08-06 05:36发布

问题:

I'm using this script to wrap two divs:

jQuery:

$("#wrapcb").click(function(){
  $('#cboxOverlay, #colorbox').wrapAll('<div class="wrapcolorbox">');
});

HTML:

<span><a id="wrapcb" href="http://www.example.com/one">First link</a></span>
<span><a id="wrapcb" href="http://www.example.com/two">Second link</a></span>
<span><a id="wrapcb" href="http://www.example.com/three">Third link</a></span>

The weird thing is that this script only works on the first link and all others are being ignored.

Any ideas what I'm doing wrong?

回答1:

That's because you've given them all the same ID (never use the same ID twice on a page). Change it to class or give each link a unique ID.

Here's an example using a common class on the links:

jQuery:

$(".wrapcb").click(function(){
  $('#cboxOverlay, #colorbox').wrapAll('<div class="wrapcolorbox">');
});

HTML:

<span><a class="wrapcb" href="http://www.example.com/one">First link</a></span>
<span><a class="wrapcb" href="http://www.example.com/two">Second link</a></span>
<span><a class="wrapcb" href="http://www.example.com/three">Third link</a></span>