如何使用 jQuery UI 以编程方式选择可选项目?

问题描述:

我有一系列可供选择的项目.我想在某处添加一个按钮来激活其中的预设选择.有没有办法做到这一点?

I have a range of items that are selectable. I would like to add a button somewhere that activates a preset selection amongst those. Is there a way I can do that?

我想要的是告诉它选择这些人",然后让所有事件正常触发,所以我不必手动调用所有这些选择事件.

What I would like is to tell it to "Select these guys" and then have all the events and all fired as normal, so I don't have to call all of those selection events manually.

更多信息:我谈论的事件是他们的api他们的演示页面:

More info: The events that I talk about are the ones listed in their api and on their demo page:

  • 已选择
  • 选择
  • 开始
  • 停止
  • 未选中
  • 取消选择

而且,我认为在选择事物时可能也会设置/清除数据.所以不仅仅是添加那些css类.

And also, I think there might be data that is set/cleared as well when selecting things. So it's not just to add those css classes.

这是 Alex R 使用多个元素的代码的变体

Here is a variation of Alex R's code working with multiple elements

http://jsfiddle.net/XYJEN/1/

function SelectSelectableElements (selectableContainer, elementsToSelect)
{
    // add unselecting class to all elements in the styleboard canvas except the ones to select
    $(".ui-selected", selectableContainer).not(elementsToSelect).removeClass("ui-selected").addClass("ui-unselecting");

    // add ui-selecting class to the elements to select
    $(elementsToSelect).not(".ui-selected").addClass("ui-selecting");

    // trigger the mouse stop event (this will select all .ui-selecting elements, and deselect all .ui-unselecting elements)
    selectableContainer.data("selectable")._mouseStop(null);
}

更新:

jQueryUI 1.10,根据 kmk 的评论:http://jsfiddle.net/XYJEN/163/

jQueryUI 1.10, per comments from kmk: http://jsfiddle.net/XYJEN/163/