<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)
}
答案 0 :(得分:3)
您需要: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)
});
&#13;
<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>
&#13;