使用 jQuery 同时交换 Div id
我有两个 div
<div id="one">xyz</div>
<div id="two">abc</div>
<input id="reverse" type="button" value="Reverse" />
单击按钮时,div 的 id 需要互换。
$('#one').attr('id', 'two');
$('#two').attr('id', 'one');
显然是假的,有人能帮我解决这个问题吗?
I have two div's
<div id="one">xyz</div>
<div id="two">abc</div>
<input id="reverse" type="button" value="Reverse" />
On click of the button, the the id's of the div needs to get interchanged.
$('#one').attr('id', 'two');
$('#two').attr('id', 'one');
would obviously be false, can anyone help me regarding this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样的东西应该有效:
演示: http://jsfiddle.net/ambigously/9zNq6/
如果您那么真的很偏执:
演示:http://jsfiddle.net/ambiguously/uQnpY/
Something like this should work:
Demo: http://jsfiddle.net/ambiguous/9zNq6/
If you're really paranoid then:
Demo: http://jsfiddle.net/ambiguous/uQnpY/
首先缓存选择器,以便它保存对元素的引用,然后交换 id 属性。
jsFiddle。
Cache the selector first so it holds a reference to the element, then swap the
id
attributes.jsFiddle.
我认为你不应该以这种方式乱搞 ID;如果是定位问题,使用类变量更有意义。您确定不能使用 addclass/removeclass 来达到您的目的吗?
出于好奇,交换两者的内容就足够了吗?
如果你想切换内容,那会很简单:
如果你真的有兴趣实际切换ID,这里有一个切换ID的例子; 使用 jQuery 更改元素的 ID
I don't think you should be messing around with IDs in that fashion; if it is a matter of positioning, using a class variable makes more sense. Are you sure you can't use addclass/removeclass for your purposes?
Out of curiousity, would switching the content of the two be sufficient?
If you wanted to switch the content, it would be pretty simple:
If you are really interested in actually switching the IDs, there is an example with switching IDs over here; Changing an element's ID with jQuery