如何在select元素的foreach循环中获取data-attribute?

时间:2016-02-01 09:35:32

标签: jquery

<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) 

}

1 个答案:

答案 0 :(得分:3)

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

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

&#13;
&#13;
$("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;
&#13;
&#13;