如何用jQuery UI以编程方式选择selectables?
我有一系列可选择的项目。 我想在某处添加一个按钮,激活其中的预设选择。 有没有办法可以做到这一点?
我想要的是告诉它“选择这些家伙”然后让所有事件和所有事件都正常触发,所以我不必手动调用所有这些选择事件。
更多信息:我所谈论的事件是他们的api和他们的演示页面中列出的事件:
- 选
- 选择
- 开始
- 停
- 未选中
- 取消选择
而且,我认为在选择内容时可能还会设置/清除数据。 所以不只是添加那些css类。
以下是Alex R的代码与多个元素一起使用的变体
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/
假设jQuery UI网站上的可选样本( http://jqueryui.com/demos/selectable/ ):
你可以有一个像这样的function:
function selectSelectableElement (selectableContainer, elementToSelect) { // add unselecting class to all elements in the styleboard canvas except current one jQuery("li", selectableContainer).each(function() { if (this != elementToSelect[0]) jQuery(this).removeClass("ui-selected").addClass("ui-unselecting"); }); // add ui-selecting class to the element to select elementToSelect.addClass("ui-selecting"); selectableContainer.selectable('refresh'); // trigger the mouse stop event (this will select all .ui-selecting elements, and deselect all .ui-unselecting elements) selectableContainer.data("selectable")._mouseStop(null); }
并使用它像:
// select the fourth item selectSelectableElement (jQuery("#selectable"), jQuery("#selectable").children(":eq(3)"));
这可以改进,以允许选择元素集合,但它是一个让你前进的起点。
你去 :
,calc: function() { this._mouseStop(); }, custom: function(guys) { var self = this; self.selectees.removeClass("ui-selected"); guys.each(function(){ $(this).addClass("ui-selecting"); self._trigger("selecting", {}, { selecting: this }); }); this.calc(); // do the selection + trigger selected }
在selectable.js
_mouseStop
之后添加此项,然后您可以说 :
$("#selectable").selectable("custom", $("#selectable :first-child"));
……或者你喜欢什么。
玩得开心 ! 🙂
编辑:对不起误解,我正在编辑我的答案。
所以,是的,对象的选择可能对应于ui选择的类,所以你可以做的是:
$(#button).click(function(){ $("#element1").addClass("ui-selected"); ....... });
是否无法使用.trigger(’selected’)手动触发selected
事件?
使用Ionut代码,如何:
$("#selectable li:first").trigger('start').trigger('selecting').trigger('selected');
?