bootstrap-multiselect 手动触发onChange事件
生活随笔
收集整理的這篇文章主要介紹了
bootstrap-multiselect 手动触发onChange事件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我們用bootstrap-multiselect去渲染select選項后,必須要手動改變選項才會觸發(fā) onChange 的回調函數,但是有時候我們需要在代碼中進行觸發(fā)onChange的回調函數。
開始想的很簡單,不就是改變select選項的值,然后 trigger("change") 嗎 ,然而并沒有有效果。
然后網上各種找,還是沒找到。行!沒找到就看源碼,我想插件肯定有考慮的這個問題。后面果然在插件中找到了相關 源碼:
/*** Select all options of the given values.** If triggerOnChange is set to true, the on change event is triggered if* and only if one value is passed.** @param {Array} selectValues* @param {Boolean} triggerOnChange*/select: function(selectValues, triggerOnChange) {if(!$.isArray(selectValues)) {selectValues = [selectValues];}for (var i = 0; i < selectValues.length; i++) {var value = selectValues[i];if (value === null || value === undefined) {continue;}var $option = this.getOptionByValue(value);var $checkbox = this.getInputByValue(value);if($option === undefined || $checkbox === undefined) {continue;}if (!this.options.multiple) {this.deselectAll(false);}if (this.options.selectedClass) {$checkbox.closest('li').addClass(this.options.selectedClass);}$checkbox.prop('checked', true);$option.prop('selected', true);if (triggerOnChange) {this.options.onChange($option, true);}}this.updateButtonText();this.updateSelectAll();if (this.options.enableClickableOptGroups && this.options.multiple) {this.updateOptGroups();}},找到源碼就簡單了,舉例子如下: $("#example-multi1").multiselect({//url:path+"/admin/demo/operdata/data.json",numberDisplayed: 100,includeSelectAllOption: true,selectAllText: '選擇全部',enableFiltering: true,buttonWidth: '100%',maxHeight: 300,onDropdownHide:function(){var ids="";var texts = '';var values = '';$('#example-multi1 option:selected').each(function() {texts += $(this).text() + ', ';values+=$(this).val() + ', ';ids+=$(this).attr("id");});},onChange:function(){console.log("onChange事件被觸發(fā)");}});var dataArr = [{label:'AAA',value:'aaa'},{label:'BBB',value:'bbb'}];$("#example-multi1").multiselect('dataprovider',dataArr); 用下面方式進行手動觸發(fā)onChange事件,注意第三個選項必須為true,如果沒有或者不是的話,就之后改變select選項的值不會觸發(fā)onChange的回調函數。$("#example-multi1").multiselect("select",["aaa"],true);
效果截圖:
總結
以上是生活随笔為你收集整理的bootstrap-multiselect 手动触发onChange事件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《明日方舟》Python版公开招募工具
- 下一篇: 基于vue框架项目开发过程中遇到的问题总