jquery两个div互换_交换jQuery中的两个元素

I'm trying to swap two elements using up and down arrows.

A JSFiddle solution would be great!

My HTML:

Some text
down
Some other text
up
down
Some text
up
down
Some other text
up

My last try was:

// 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));

}

});

I've tried a lot of different ways to change items. I've tried with replaceWith(), before(), and after() but nothing worked.

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.

解决方案

You can do it like this - you need to check e.target not the div with class = move

jQuery('.move').children().click(function (e) { //

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

}

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值