2012-09-20 24 views
2

我一直在寻找类似于我想要实现的东西,但没有在堆栈或网络中找到它。 使用jQuery可选的,但有一组以上的UL年代:jquery selectable - 禁用对应的值

<div> 
    <ul> 
     <li>1</li> 
     <li>2</li> 
     <li>3</li> 
     <li>4</li> 
    </ul> 
    <ul> 
     <li>1</li> 
     <li>2</li> 
     <li>3</li> 
     <li>4</li> 
    </ul> 
    <ul> 
     <li>1</li> 
     <li>2</li> 
     <li>3</li> 
     <li>4</li> 
    </ul> 
</div> 

什么,我希望能够做的是,如果我从任何的选项中选择“1”,其他所有的“1'被禁用。所有其他选择选项也是如此,因此基本上,您一次只能选择一个相同的选项。 我可以使用单选按钮,使用名称和值标签,但不确定如何在可选界面中实现它? 感谢任何帮助,或者如果有人可以指点我一个类似的应用程序。

回答

0

您只能使用filter选项选择一些项目。更改完成后,您需要遍历所有元素并根据需要更新过滤器。

样品的实现可能是这样的(见现场演示here):

$(document).ready(function() { 

    function enableAll() { 
     $('li').addClass('enabled'); 
    } 

    function disableSelected(selected) { 

     // iterate thru all list items 
     $.each($('li'), function(i, item) { 

      // if the text is selected somewhere.. 
      if ($.inArray($(this).text().toLowerCase(), selected) >= 0) { 

       // ..and it's not here 
       if (!$(this).hasClass('ui-selected')) { 

        // remove 
        $(this).removeClass('enabled'); 
       } 
      } 
     }); 
    } 

    $('ul').selectable({ 

     // only matching items will be selectable 
     filter: '.enabled', 

     // change handler 
     stop: function(event, ui) { 

      // we will collect selected texts in this variable 
      var selectedTexts = new Array(); 

      // go thru all selected items (not only in current list) 
      $('.ui-selected').each(function() { 

       // extract selected text 
       var text = $(this).text().toLowerCase(); 

       // add to array if not already there 
       if ($.inArray(text, selectedTexts) < 0) { 
        selectedTexts.push(text); 
       } 
      }); 

      // enable all list items for selectable 
      enableAll(); 

      // disable list items with text that is already selected 
      disableSelected(selectedTexts); 
     } 
    }); 

    // initialization 
    enableAll(); 

});​ 
+0

感谢花花公子。我明白你的意思与过滤器选项只适用于一些禁用。例如,当我在第一个,第二个中点击4时,我仍然可以在第三个中点击2。我还是比较新的JavaScript/jQuery的,所以我会研究你的示例,看看语言过程。我想要做的是有一个输出元素,就像我猜的购物车,从而显示每个列表中的选择,并且每个数字只能有一个代表。再次感谢。 – user1648449