wrapAll() only working on the first element?

孤街浪徒 提交于 2019-12-24 14:25:40

问题


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>


来源:https://stackoverflow.com/questions/15605141/wrapall-only-working-on-the-first-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!