jquery - 变量作为函数的参数

时间:2021-11-13 00:38:54

I have a multiple select:

我有一个多选:

<select name="courier" class="selectpicker courierpicker" multiple>
    <option value="value1">Value1</option>
    <option value="value2">Value2</option>
    ...
</select>

I want to use selected options as parameters for filtering rows in my table. This code doesn't work for me (assume, just for this example, that there is always more than one selected option):

我想使用选定的选项作为过滤表格中的行的参数。此代码对我不起作用(假设,仅为此示例,始终有多个选定的选项):

$(".selectpicker").change(function() {
    var items = [];
    $('.courierpicker option:selected').each(function(){ 
        items.push($(this).val()); 
    });
    var $result = '["' + items.join('","') + '"]';
    $('#data-table').bootstrapTable('filterBy', {
        courierfilter: $result
    });
});

When I trigger:

当我触发时:

$('#data-table').bootstrapTable('filterBy', { 
    courierfilter: ["value1","value2"] 
});

Everything works just fine.

一切正常。

I know it will be some stupid mistake of the beginner, but thanks in advance for every help.

我知道初学者会犯一些愚蠢的错误,但要事先感谢每一个帮助。

2 个解决方案

#1


1  

The issue is because the courierfilter property expects an array, yet you're providing it a string which is formatted like an array. Also note that the array generation can be made simpler through the use of the map() method. Try this:

问题是因为courierfi​​lter属性需要一个数组,但是你要为它提供一个格式化为数组的字符串。另请注意,通过使用map()方法可以使数组生成更简单。试试这个:

$(".selectpicker").change(function() {
    var items = $('.courierpicker option:selected').map(function(){ 
        return this.value;
    }).get();
    $('#data-table').bootstrapTable('filterBy', {    
        courierfilter: items 
    });
});

#2


1  

Just use {courierfilter: items}.

只需使用{courierfi​​lter:items}即可。

#1


1  

The issue is because the courierfilter property expects an array, yet you're providing it a string which is formatted like an array. Also note that the array generation can be made simpler through the use of the map() method. Try this:

问题是因为courierfi​​lter属性需要一个数组,但是你要为它提供一个格式化为数组的字符串。另请注意,通过使用map()方法可以使数组生成更简单。试试这个:

$(".selectpicker").change(function() {
    var items = $('.courierpicker option:selected').map(function(){ 
        return this.value;
    }).get();
    $('#data-table').bootstrapTable('filterBy', {    
        courierfilter: items 
    });
});

#2


1  

Just use {courierfilter: items}.

只需使用{courierfi​​lter:items}即可。