javascript 如何从选择选项中获取 HTML5 数据值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12126815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get an HTML5 data value from a select option?
提问by dcolumbus
Is it possible to use jquery to get an html5 data attribute from a select option?
是否可以使用 jquery 从选择选项中获取 html5 数据属性?
<select id="change-image">
<option value="cool" data-image="myimage.jpg">Cool</option>
</select>
$("#pet-tag-id").change(function() {
var src = $("#change-image").data("image");
$("#image-preview").attr("src", src);
});
<img id="image-preview">
回答by jAndy
Yes.
是的。
You even did it in the correct manner. jQuery will pull HTML5 data attributesinto its internal expando data objectfor elements. So you can access them just by name.
你甚至以正确的方式做到了。jQuery 会将HTML5 数据属性拉入其元素的内部 expando数据对象。因此,您可以仅通过名称访问它们。
The only thing that is incorrect is, that you don't call .data()
on the correct element. You're calling it on the <select>
, but you need to grab the selected option element. Like
唯一不正确的是,您没有调用.data()
正确的元素。您在 上调用它<select>
,但您需要获取选定的选项元素。喜欢
var src = $("#change-image option:selected").data("image");
回答by orhanhenrik
$("#change-image").change(function() {
var data_image = $(this).children('option:selected').attr('data-image');
});
?
?