如何获取选项选定数据标记

时间:2015-06-02 19:34:06

标签: javascript jquery

我可以获取文本和值,但我想获得另一个标记

this.options[this.selectedIndex].value <---will get the value

this.options[this.selectedIndex].text   <---will get the text

我想从此选项中获取data_id

<option value="L W12 6.3 quattro" data-id="200480476">L W12 6.3 quattro</option>

我试过了:

this.options[this.selectedIndex].data-id

并且没有工作

对不起,我将添加更多信息...我在ruby on rails上的嵌套表单上使用它,并为它设置了一个on change事件:

<select id="shipment_vehicles_attributes_0_style" name="shipment[vehicles_attributes][0][style]" onchange="getStylesId(this.id,this.options[this.selectedIndex].data-id)"><option value="">Select A Style</option><option value="Base" data-id="9058">Base</option></select>

我可以在那里使用jquery

3 个答案:

答案 0 :(得分:1)

您的代码表明您使用的是jQuery。然后你可以这样做:

var attr = $('option:selected').attr( "data-id" );

答案 1 :(得分:0)

你可以使用jquery的.attr()。

    $("option").attr('data_id')

答案 2 :(得分:0)

提到的jQuery方法工作得很好。但是如果你想使用通常更快的vanilla JS,那么你需要使用getAttribute方法:

  var x = this.options[this.selectedIndex];
  alert( x.getAttribute('data-id') );

这是fiddle