如何从下拉菜单中选择的选项获得标题属性的值

How to get value of title attribute from a selected option in DropDown

本文关键字:标题 属性 选项 下拉菜单 选择      更新时间:2023-09-26

我有一个html select元素,其中包括三个option元素。我已经编写了一个jquery代码,它从当前选择的选项元素中为我提供了title属性的值,并将该值保存在一个变量中(动态地)。

但是我想从一个选项值中读取标题属性,该选项值没有被选中,并且已经在我的xhtml页面中显示为选中值,如果页面被加载为第一页。

这是我的jQuery代码,第二个代码不能正常工作:

$(document).ready(function(){
   var optionElements = jQuery(jQuerySelektorHTMLSelectElement).children();
   var OptionField = optionElements.find("[value=" + selectedValue + "]");
   var OptionFieldTitleAttribut = OptionFeld.attr("title"); 
}

如果加载了xhtml页面,我如何找到一个未动态选中但已选中的选项元素?

如果变量jQuerySelektorHTMLSelectElement命名良好,则不必调用children:

var selectElement = $(jQuerySelektorHTMLSelectElement); // <- remove children here
var OptionField = selectElement.find("[value=" + selectedValue + "]");
var OptionFieldTitleAttribut = OptionField.attr("title"); 

find方法已经在子元素中查找选择器…

试试这个:

<select id="test">
    <option customAttr="a">test1</option>
    <option customAttr="b">test2</option>
    <option customAttr="c" selected="selected">test3</option>
    <option customAttr="d">test4</option>
</select>

js

$(function(){
  console.log($("#test").find("option:selected").attr("customAttr"));
});

小提琴