交换Div id';s同时使用jQuery
我有两个div交换Div id';s同时使用jQuery,jquery,jquery-ui,jquery-selectors,Jquery,Jquery Ui,Jquery Selectors,我有两个div <div id="one">xyz</div> <div id="two">abc</div> <input id="reverse" type="button" value="Reverse" /> 这显然是错误的,有人能帮我吗?首先缓存选择器,使其保存对元素的引用,然后交换id属性 var one = $('#one'); $('#two').attr('id', 'one'); one.a
<div id="one">xyz</div>
<div id="two">abc</div>
<input id="reverse" type="button" value="Reverse" />
这显然是错误的,有人能帮我吗?首先缓存选择器,使其保存对元素的引用,然后交换
id
属性
var one = $('#one');
$('#two').attr('id', 'one');
one.attr('id', 'two');
.类似的方法应该可以:
$('#reverse').click(function() {
var $one = $('#one');
var $two = $('#two');
$one.attr('id', 'two');
$two.attr('id', 'one');
});
演示:
如果你真的很偏执,那么:
$('#reverse').click(function() {
var $one = $('#one');
var $two = $('#two');
$one.removeAttr('id');
$two.attr('id', 'one');
$one.attr('id', 'two');
});
演示:我认为你不应该以那种方式乱搞ID;如果是定位问题,那么使用类变量更有意义。您确定不能出于您的目的使用addclass/removeclass吗 出于好奇,切换这两个的内容就足够了吗 如果您想切换内容,它将非常简单:
function switch_contents(){
var one_contents = $('#one').html();
$('#one').html($('two').html());
$('#two').html(one_contents);
}
如果你真的对切换ID感兴趣,这里有一个切换ID的例子 感谢您的回答,我是jQuery新手,您为我提供了解决方案的替代方案。切换
innerHTML
很少是理想的。感谢Alex,我没有意识到这一点。感谢您让我知道如何缓存选择器。它工作得很好。
function switch_contents(){
var one_contents = $('#one').html();
$('#one').html($('two').html());
$('#two').html(one_contents);
}