jQuery过滤器不返回数据元素,只返回整个对象

jQuery filter not returning data element, only entire object

本文关键字:返回 对象 元素 过滤器 数据 jQuery      更新时间:2023-09-26

我正在尝试从<select>filter()一个jQuery列表,如果文本匹配,则返回一个data属性。匹配有效,但我没有得到数据属性中包含的字符串:我得到了整个对象

$("#company_select option").filter(function(){
    var d = $(this).data("company_system_name");
    if ($(this).text() === val ) { return  d; };
})

为什么会发生这种情况。如何返回数据属性?

看起来您想要:

var optData = $("#company_select option").filter(function(){
    return $(this).text() === val;
}).data("company_system_name");

$.fn.filter方法返回过滤后的jQuery集合。根据您想要的内容,您可以获取第一个过滤后的元素数据或所有数据属性作为数组:

var $options = $("#company_select option").filter(function() {
    return $(this).text() === val;
});
// Get the data of the first filtered option
var firstData = $options.data('company_system_name');
// Get an array of all data attributes
var allData = $options.map(function() {
    return $(this).data("company_system_name");
}).get();

Filter用于根据您选择的条件减少一组匹配的元素。要真正从他们那里获得数据,你需要这样做:

var d = $("#company_select option").filter(function(){
    return $(this).text() == val;
}).data('company_system_name');

尝试

var val = "a"
    , _data = $.map($("#company_select option"), function(el, i) {
                  return $(el).text() === val 
                         ? $(el).data("company_system_name")
                         : null
              });
console.log(_data)

var val = "a"
    , _data = $.map($("#company_select option"), function(el, i) {
    return $(el).text() === val 
      ? $(el).data("company_system_name")
      : null
})
console.log(_data)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="company_select">
    <option data-company_system_name="a">a</option>
    <option data-company_system_name="b">b</option>
    <option data-company_system_name="b">b</option>
</select>