【问题标题】:Swap contents from two different lists by clicking on both list items通过单击两个列表项来交换两个不同列表中的内容
【发布时间】:2013-12-24 17:51:06
【问题描述】:

我想交换两个不同列表中的元素。因此,如果我在左侧列表和右侧列表中选择某些内容,它们需要交换。

目前看起来像这样: html:

<ul id="sortable1" class="connectedSortable">
    <li value="1" class="ui-state-default">Sort1 Item 1</li>
    <li value="2" class="ui-state-default">Sort1 Item 2</li>
    <li value="3" class="ui-state-default">Sort1 Item 3</li>
    <li value="4" class="ui-state-default">Sort1 Item 4</li>
    <li value="5" class="ui-state-default">Sort1 Item 5</li>
</ul>

<ul id="sortable2" class="connectedSortable">
    <li value="1" class="ui-state-highlight">Sort2 Item 1</li>
    <li value="2" class="ui-state-highlight">Sort2 Item 2</li>
    <li value="3" class="ui-state-highlight">Sort2 Item 3</li>
    <li value="4" class="ui-state-highlight">Sort2 Item 4</li>
    <li value="5" class="ui-state-highlight">Sort2 Item 5</li>
</ul>

jquery:

var testClickSort1 ='';
var testClickSort2 ='';

$(function() {
    $("#sortable1").sortable({
        cursor: 'pointer',
        connectWith: ".connectedSortable"
    }).disableSelection();

$("#sortable2").sortable({
    cursor: 'pointer',
    connectWith: ".connectedSortable"
}).disableSelection();

$("#sortable1 li").on('click',function(){
       // $("#testClickSort1").html($(this).attr('value'));
        testClickSort1 = $(this).attr('value'); 
        test();
});

$("#sortable2 li").on('click',function(){
       // $("#testClickSort2").html($(this).attr('value'));
        testClickSort2 = $(this).attr('value');
        test();
});
});

 function test(){ 
      if ((testClickSort1 != "") && (testClickSort2 != "")) {
         alert ("test: " + testClickSort1 + '' +  testClickSort2);
         //function to swap testclicksort1 with testclicksort2
         testClickSort1 = '';
         testClickSort2 = '';
}   
}

可以在这里查看:

http://jsfiddle.net/qkCcS/26/

现在我需要知道用 testclicksort2 交换 testclicksort1 的功能是什么。

提前致谢。

你好,

沃特

【问题讨论】:

  • 完全更新了我的代码。取得一些进展!

标签: jquery list onclick swap items


【解决方案1】:

不要使用&gt; 直接后代选择器。另外我建议您使用.data() 而不是.attr()

代替

 $("ul.icecream>li.active")

使用

 $("ul.icecream li.active")

DEMO

竞争代码

function swap(){
    if($("ul.icecream>li").hasClass("active")){
        var p1_name = $("ul.icecream li.active").data("name");
        var p_name = $(this).data("name");
        $(this).data("name", p1_name).text(p1_name);
        $("ul.icecream li.active").data("name", p_name).text(p_name).removeClass("active");
    }
    else{
        $(this).addClass("active");
    }
}
$("ul.icecream>li").on("click", swap);

【讨论】:

  • 感谢您的改进!我仍然想知道如何获得两个单独的无序列表而不是一个。因为我需要将另一个列表的样式完全不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
相关资源
最近更新 更多