如何使用 jquery 获取选项 title="sample"

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2791400/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:16:59  来源:igfitidea点击:

how to get option title="sample" using jquery

jqueryselectoptionattr

提问by tom

I'm trying to update a hidden field based on the a title attribute on a select option, I've tried the code bellow and can't seem to get it to work. Thanks for any help!

我正在尝试根据选择选项上的标题属性更新隐藏字段,我已经尝试了下面的代码,但似乎无法让它工作。谢谢你的帮助!

<form>
    <select id="selectbox">
        <option name="test" value="one" title="title" selected="selected">one</option>
        <option name="test2" value="two" title="title2">two</option>
    </select>
</form>
<input id="update" type="hidden" value="defaultold" />

<script>
    $('#update').val('default');
    $('#selectbox').change(function() {
        $('#update').val($(this).attr("title"));
    });
</script>

回答by karim79

Encapsulate that code within a $(document).ready(...block, and you need to use the option'stitle:

将该代码封装在一个$(document).ready(...块中,您需要使用该选项的标题:

$(document).ready(function() {
    $('#update').val('default');   
    $('#selectbox').change(function() {
         $('#update').val($(this).find("option:selected").attr("title"));
    });
});

$(this)refers to the context of the select element, you can use findto get the descendant of interest which in this case is the selected option.

$(this)指的是 select 元素的上下文,您可以使用它find来获取感兴趣的后代,在这种情况下是选定的选项。

回答by Hamid

Accessing the text of selected option using jquery:

使用 jquery 访问所选选项的文本:

var title = $( "#myselectId option:selected" ).text();