Javascript 如何在选择控件中获取选定项的文本? 服务器1:3000 服务器3:3000
我知道在prototype中,我可以通过Javascript 如何在选择控件中获取选定项的文本? 服务器1:3000 服务器3:3000,javascript,prototypejs,Javascript,Prototypejs,我知道在prototype中,我可以通过$('serverDropList')获得值。值但我如何获得“server1:3000”?我认为prototype没有任何快捷方式可以为您实现这一点,因此: <select name="DropList" id="serverDropList"> <option selected="selected" value="2">server1:3000</option> <option value="5"&
$('serverDropList')获得值。值
但我如何获得“server1:3000”?我认为prototype没有任何快捷方式可以为您实现这一点,因此:
<select name="DropList" id="serverDropList">
<option selected="selected" value="2">server1:3000</option>
<option value="5">server3:3000</option>
</select>
…为您提供所选选项的innerHTML
,如果没有,则提供undefined
如果愿意,可以使用定义一次,并在所有选择框中提供:
var box = $('serverDropList');
var text = box.selectedIndex >= 0 ? box.options[box.selectedIndex].innerHTML : undefined;
用法:
Element.addMethods("SELECT", (function() {
function getSelectedOptionHTML(element) {
if (!(element = $(element))) return;
var index = element.selectedIndex;
return index >= 0 ? element.options[index].innerHTML : undefined;
}
return {
getSelectedOptionHTML: getSelectedOptionHTML
};
})());
function getSelectedValue( obj ) {
return obj.options[obj.selectedIndex].value;
}
我在定义时使用了一个命名函数。如果您对命名函数(我是,我是)不感兴趣,您可以将其简化一点:
var text = $('serverDropList').getSelectedOptionHTML();
如果您使用的是Prototype,您可以使用:
Element.addMethods("SELECT", {
getSelectedOptionHTML: function(element) {
if (!(element = $(element))) return;
var index = element.selectedIndex;
return index >= 0 ? element.options[index].innerHTML : undefined;
}
);
用法:
Element.addMethods("SELECT", (function() {
function getSelectedOptionHTML(element) {
if (!(element = $(element))) return;
var index = element.selectedIndex;
return index >= 0 ? element.options[index].innerHTML : undefined;
}
return {
getSelectedOptionHTML: getSelectedOptionHTML
};
})());
function getSelectedValue( obj ) {
return obj.options[obj.selectedIndex].value;
}
或者(使用prototype或jquery时)
很抱歉,如果我迟了回答这个问题,但是我正在研究同一个问题,我对这个答案不满意,所以我想找到一个更好的答案: Prototype具有以下选择器,您可以使用它来获取列表中的选定值:$F。 因此,在您的示例情况中,它应该使用以下代码:
getSelectedValue($('mySelect'));
选择第二个选项:
$F('serverDropList'); -- this for getting the value
$F('serverDropList').text; -- this for getting the text
value=“1”city=“芝加哥”>一个
value=“2”city=“orlando”>两个
我需要选择“城市价值”项目。这要好多了。。有没有一种方法可以将它与onchange创建的
这个
混搭在一起?我不太确定是否所有浏览器都支持此功能,因此您可以检查一下,否则您可能会犯错误,提交一个提琴以便我可以帮助您的原因这不会返回文本值,但是所选项目的值
属性。OP询问所选选项的文本值。这应该是正确答案。完美的
$F('serverDropList'); -- this for getting the value
$F('serverDropList').text; -- this for getting the text
<select onchange="alert(getSelectedValue(this););" id="mySelect">
<option> value="1" city="chicago"> one </option>
<option> value="2" city="orlando"> two </option>
</select>