gpt4 book ai didi

jquery - 如何在选择元素的 foreach 循环中获取数据属性?

转载 作者:行者123 更新时间:2023-12-01 07:47:16 26 4
gpt4 key购买 nike

<tr class="font-titlerow">    
<td class="fontname-col">
<select>
<option data-fontfamily="Abel" value="1">Abel</option>
<option data-fontfamily="Arial" value="2">Arial</option>
<option data-fontfamily="Arial+Black" value="3">Arial Black</option>
</select>
</td>
</tr>

<tr class="font-titlerow">
<td class="fontname-col">
<select>
<option data-fontfamily="Abel" value="1">Abel</option>
<option data-fontfamily="Arial" value="2">Arial</option>
<option data-fontfamily="Arial+Black" value="3">Arial Black</option>
</select>
</td>
</tr>

如何在 jQuery 中循环选择并获取 data-fontfamily?

$("tr.font-titlerow").each(function(index) {       
var drow = $(this);

var fontselect =drow.find("td.fontname-col").find("select");
var fontname = fontselect.val(); //This gives the value... (1,2 or 3 in example)
var fontfamily = fontselect.attr('data-fontfamily'); //Does not work (obviously)

}

最佳答案

您需要:selected selector ,因为自定义属性 fontfamily 是在 option 元素上定义的,而不是在 select 元素上定义的。

var fontfamily = fontselect.find('option:selected').data('fontfamily');

$("tr.font-titlerow").each(function(index) {
var drow = $(this);

var fontselect = drow.find("td.fontname-col").find("select");
var fontname = fontselect.val(); //This gives the value... (1,2 or 3 in example)
var fontfamily = fontselect.find(':selected').data('fontfamily');
snippet.log(fontfamily)

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<table>
<tr class="font-titlerow">
<td class="fontname-col">
<select>
<option data-fontfamily="Abel" value="1">Abel</option>
<option data-fontfamily="Arial" value="2">Arial</option>
<option data-fontfamily="Arial+Black" value="3">Arial Black</option>
</select>
</td>
</tr>
</table>

关于jquery - 如何在选择元素的 foreach 循环中获取数据属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35127098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com