交换jQuery中的两个元素 [英] Swap two elements in jQuery
问题描述
我正在尝试使用向上和向下箭头交换两个元素.
I'm trying to swap two elements using up and down arrows.
JSFiddle解决方案会很棒!
A JSFiddle solution would be great!
我的HTML:
<div class="item">
<div class="content">Some text</div>
<div class="move">
<div class="move-down">down</div>
</div>
</div>
<div class="item">
<div class="content">Some other text</div>
<div class="move">
<div class="move-up">up</div>
<div class="move-down">down</div>
</div>
</div>
<div class="item">
<div class="content">Some text</div>
<div class="move">
<div class="move-up">up</div>
<div class="move-down">down</div>
</div>
</div>
<div class="item">
<div class="content">Some other text</div>
<div class="move">
<div class="move-up">up</div>
</div>
</div>
我最后一次尝试是:
// el is the clicked one.
jQuery('.move').children().click(function(el) {
if (jQuery(el).hasClass('move-down') === true) {
el = jQuery(el).parent().parent();
el.prependTo(el.after(el));
} else {
el = jQuery(el).parent().parent();
el.appendTo(el.before(el));
}
});
我尝试了许多不同的方式来更改项目.我已经尝试过使用replaceWith()
,before()
和after()
,但是没有任何效果.
I've tried a lot of different ways to change items. I've tried with replaceWith()
, before()
, and after()
but nothing worked.
注意: 我已经编写了一个显示正确的上/下DIV的函数.因此,第一个和最后一个只能朝一个方向移动.已经解决了.我也不能使用任何现有的jQuery插件.
NOTICE: I've already written a function which displays the correct up / down DIVs. So the first and last one can only moved in one direction. That's already solved. I also can't use any kind of existing jQuery plugins.
推荐答案
您可以这样做-您需要检查e.target而不是class = move的div
You can do it like this - you need to check e.target not the div with class = move
jQuery('.move').children().click(function (e) { // <-- argument passed in is the event not an element
var $div = $(this).closest('.item'); // get closest item div
if (jQuery(e.target).is('.move-down')) { // check if clicked is movedown
$div.next('.item').after($div); // if it is move after next
} else {
$div.prev('.item').before($div);// else move it before previous
}
});
这篇关于交换jQuery中的两个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!