I have an html select
element, which includes three option
elements. I have written a jquery code, which gives me the value of the title attribut from the current selected option element and saves that value in a variable (on the fly!).
我有一个html选择元素,其中包含三个选项元素。我编写了一个jquery代码,它给出了当前所选选项元素的标题attribut的值,并将该值保存在变量中(动态!)。
But I would like to read a title attribute from an option value, which was not selected on the fly and which was already shown as selected value in my xhtml page, if the page was loaded as first.
但我想从一个选项值中读取一个title属性,如果页面是作为第一个加载的,那么这个选项值没有在动态选择,并且已经在我的xhtml页面中显示为选定值。
This is my jQuery code and the second coderow doesn´t work correct:
这是我的jQuery代码,第二个coderow不正确:
$(document).ready(function(){
var optionElements = jQuery(jQuerySelektorHTMLSelectElement).children();
var OptionField = optionElements.find("[value=" + selectedValue + "]");
var OptionFieldTitleAttribut = OptionFeld.attr("title");
}
How can I find an option element, which was not selected on the fly but is selected, if the xhtml page was loaded?
如果加载了xhtml页面,我怎样才能找到一个选项元素,该元素未动态选择但被选中?
2 个解决方案
#1
3
If your variable jQuerySelektorHTMLSelectElement
is well-named, you don't have to call children
:
如果变量jQuerySelektorHTMLSelectElement具有良好的名称,则不必调用子项:
var selectElement = $(jQuerySelektorHTMLSelectElement); // <- remove children here
var OptionField = selectElement.find("[value=" + selectedValue + "]");
var OptionFieldTitleAttribut = OptionField.attr("title");
The find
method already look for the selector in the children...
find方法已经在子节点中查找选择器...
See this fiddle.
看到这个小提琴。
#2
1
Try this:
尝试这个:
html
HTML
<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
JS
$(function(){
console.log($("#test").find("option:selected").attr("customAttr"));
});
小提琴
#1
3
If your variable jQuerySelektorHTMLSelectElement
is well-named, you don't have to call children
:
如果变量jQuerySelektorHTMLSelectElement具有良好的名称,则不必调用子项:
var selectElement = $(jQuerySelektorHTMLSelectElement); // <- remove children here
var OptionField = selectElement.find("[value=" + selectedValue + "]");
var OptionFieldTitleAttribut = OptionField.attr("title");
The find
method already look for the selector in the children...
find方法已经在子节点中查找选择器...
See this fiddle.
看到这个小提琴。
#2
1
Try this:
尝试这个:
html
HTML
<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
JS
$(function(){
console.log($("#test").find("option:selected").attr("customAttr"));
});
小提琴