在jQueryUI中只选择一个可选项

Select only one selectable with jQueryUI

本文关键字:一个 可选项 jQueryUI 选择      更新时间:2023-09-26

我有一个序列化的可选项,我想要一个函数使它一次只选择一个列表项。我相信我有正确的密码,但它不起作用。有人知道为什么吗?

这是我的javascript:

$(function() {
    $( "#selectable" ).selectable({
        stop: function() {
            var result = $( "#select-result" ).empty();
            $( ".ui-selected", this ).each(function() {
                var index = $( "#selectable li" ).index( this );
                result.append( " #" + ( index + 1 ) );
            });
        }
    });
});

$("#selectable").selectable({
      selected: function(event, ui) {
            $(ui.selected).siblings().removeClass("ui-selected");
      }
});

我的选择从html如下。也许有一个问题,由于元素嵌套在<li>标签?

<ul id="selectable">
    <li><a><img src="images/CacheMenuGoogleCache2.png", alt="Google Cache" class="button" id="Google Cache" height ="34px" /></a></li>
    <li><a><img src="images/CacheMenuBingCache2.png", alt="Bing Cache" class="button" id="Bing Cache" height ="34px" /></a></li>
    <li><a><img src="images/CacheMenuYahooCache2.png", alt="Yahoo Cache" class="button" id="Yahoo Cache" height ="34px" /></a></li>
    <li><a><img src="images/CacheMenuWaybackMachine2.png", alt="WayBack Machine" class="button" id="WayBack Machine" height ="34px" /></a></li>
    <li><a><img src="images/CacheMenuCoralCDN2.png", alt="CoralCDN" class="button" id="CoralCDN" height ="34px" /></a></li>
    <li><a><img src="images/CacheMenuGigablast2.png", alt="Gigablast" class="button" id="Gigablast" height ="34px" /></a></li>
    <li><a><img src="images/CacheMenuWebCite2.png", alt="Webcite" class="button" id="Webcite" height ="34px" /></a></li>
</ul>
我感谢你的时间和你的帮助!

好了,我找到问题了。我需要将它包含在一个函数中,像这样:

$(function() {
    $("#selectable").selectable({
        selecting: function(event, ui){
            if( $(".ui-selected, .ui-selecting").length > 1){
                  $(ui.selecting).removeClass("ui-selecting");
            }
        }
    });
});

另外,您可能会注意到函数有一点不同。