繁体   English   中英

我如何获得“选择的数据”标签

[英]How do i get Option Selected Data tag

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

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

没用

抱歉,我将添加更多信息...我在Rails上的ruby嵌套表单中使用此控件,并为其设置了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吗

您的标签表明您正在使用jQuery。 然后,您可以执行以下操作:

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

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

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

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

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

这是一个小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM