通过变量选择数据属性名称



我无法弄清楚正确的语法是什么:

<select>
    <option data-option1="test"></option>
</select>

jQuery(其中索引是一个贯穿循环(:

$('fieldset').each(function(index, element){
   var name = 'option'+index;
   var res = $('select').find(':selected').data(name);
   console.log(res);
});

这些工作:

var name = 'option1';
var name = 'option'+1;

这没有(索引肯定正确注册,因为我使用它来选择其他元素(:

var name = 'option'+index;

我尝试更改为 String(( 等以防万一,但无法弄清楚。如果我只使用名称,例如 data('option1'(,但它有效,但当它是一个变量时就不行了

select 元素没有 data-option1 属性。

您不仅需要询问正确的数据属性,还需要从实际具有该属性的元素中询问它:

let index = 1
let name = 'option' + index
console.log($(`select option[data-${name}]`).data(name));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
    <option data-option1="test"></option>
</select>

您可以使用

$("option").data(name);来获取数据属性值。此外,该属性是打开选项而不是选择,因此请使用正确的选择器。

var index = 1;
var name = "option"+index;
var res = $("select option").eq(index-1).data(name);
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
    <option data-option1="test"></option>
</select>

最新更新