使用循环移动列表中的选中项

时间:2014-01-30 22:35:29

标签: javascript list loops transfer

我有两个无序列表,列表项目里面有复选框。我想一次将所有检查项目移到另一侧。目前它只是一次移动一个,或偶尔移动两个,并给我错误。我认为我的循环存在问题?

http://jsfiddle.net/XJ82y/

<form action="" method="get" name="formName">

<div class="list" id="select1_wrapper">

<ul id="select1">
<li><label>
  <input type="checkbox" value="checkbox" id="CheckboxGroup1_0" class="movethis" />
  <span>Lime</span></label>        
  </li>
</ul>
</div>

 <div class="middle_column_options" style="float:left; width: 60px; padding-top:10px;">
 <a href="#" id="add" onclick="javascript:moveRight(); return false;">Move items to the right</a>
 <hr />
 <a href="#" id="remove" onclick="javascript:moveLeft(); return false;">Move items to the left</a>
 </div>

<div class="list" id="select2_wrapper">

<ul id="select2">
<li><label>
  <input type="checkbox" value="checkbox" id="CheckboxGroup2_0" class="movethis" />
  <span>Banana</span></label>
      </li>
<li><label> 
  <input type="checkbox" value="checkbox" id="CheckboxGroup2_1" class="movethis" />
  <span>Pear</span></label>
      </li>
</ul>
</div>
</form>

的javascript:

//move function
function moveLeft () {
    var selectlist = document.getElementById('select2');
    var hom = selectlist.getElementsByTagName("li");
    var homs = selectlist.getElementsByTagName("li").length; //count the number of list items and set as homs
    for (var i=0;i<homs;i++){
      var subcheck = hom[i].getElementsByTagName('input')[0];

      if (subcheck.checked) {
        document.getElementById('select1').appendChild(hom[i]);
    } 


    };
};

function moveRight () {
    var selectlist = document.getElementById('select1');
    var hom = selectlist.getElementsByTagName("li");
    var homs = selectlist.getElementsByTagName("li").length; //count the number of list items and set as homs
    for (var i=0;i<homs;i++){
      var subcheck = hom[i].getElementsByTagName('input')[0];

      if (subcheck.checked) {
        document.getElementById('select2').appendChild(hom[i]);
    } 


    };
};

请不要jquery回答!寻找仅限javascript的解决方案。

1 个答案:

答案 0 :(得分:1)

正如Evan所说,你在迭代它时修改列表。如果你单独构建列表,然后迭代它(因为它在移动元素时不会收缩)它将起作用。一个简单的例子:

//move function
function moveLeft () {
    var selectlist = document.getElementById('select2');
    var hom = selectlist.getElementsByTagName("li");
    var homs = selectlist.getElementsByTagName("li").length;
    var toMove = [];
    //count the number of list items and set as homs
    for (var i=0;i<homs;i++){
        var subcheck = hom[i].getElementsByTagName('input')[0];
    if (subcheck.checked) {
           toMove.push(hom[i]);     
        }
    };
    for (var i = 0; i < toMove.length; i++) {
      document.getElementById('select1').appendChild(toMove[i]);
    }
};