如何知道一个<;选项>;使用JavaScript中的特定内容?
我做了很多搜索,但我不能解决我的问题如何知道一个<;选项>;使用JavaScript中的特定内容?,javascript,select,option,Javascript,Select,Option,我做了很多搜索,但我不能解决我的问题 <select id="my_select"> <option value="Findme_1">Knowing_1 <option value="Findme_2">Knowing_2 </select> 认识你1 了解你2 在函数中,我需要查找内容中带有“Findme_1”的选项的值 请问我怎么做 编辑:我不需要查找所选选项的值,也不需要使用其索引查找选项的值,我只知道内容“Knowi
<select id="my_select">
<option value="Findme_1">Knowing_1
<option value="Findme_2">Knowing_2
</select>
认识你1
了解你2
在函数中,我需要查找内容中带有“Findme_1”的选项的值
请问我怎么做
编辑:我不需要查找所选选项的值,也不需要使用其索引查找选项的值,我只知道内容“Knowing_1”,我想知道值“Findme_1”
我考虑过循环,但可能还有其他更常见的方法吗?使用此方法
使用SelectedIndex属性 这将提醒所选选项的值:
(function() {
var select = document.getElementById('my_select');
select.addEventListener('change', function(){
alert( select.options[select.selectedIndex].value );
});
})();
此外,还应关闭选项元素:
<select id="my_select">
<option value="Test_1">Findme_1</option>
<option value="Test_2">Findme_2</option>
</select>
Findme_1
Findme_2
完整代码和预览:首先,您的html不正确,缺少关闭标记。应该是这样的
<select id="my_select">
<option value="Test_1">Findme_1 </option>
<option value="Test_2">Findme_2 </option>
</select>
Findme_1
Findme_2
然后我猜,您希望在用户选择下拉菜单时通过javascript获得值,所以现在编写javascript
<script>
document.getElementById('my_select').onchange = function(){
var my_value = this.value; // you have your new value on the variable my_value
};
</script>
document.getElementById('my_select')。onchange=function(){
var my_value=this.value;//变量my_value上有新值
};
要通过文本查找
,您可以循环并检查(标准)或(即,非标准):
示例:在发布问题之前,请检查答案。已经有帖子,因此如果您可以使用jQuery,请查看是,很抱歉没有说,但我可以使用jQuery。你的答案看起来很好,我会在我的脚本中检查这一点,谢谢。编辑我的答案以反映其他人的正确解决方案。我对所选选项不感兴趣,我正在处理选项的“内容”。你如何获得内容?
<script>
document.getElementById('my_select').onchange = function(){
var my_value = this.value; // you have your new value on the variable my_value
};
</script>
function valueByText(select, text) {
var options = select.options;
var textContent;
for (var i = 0, l = options.length; i < l; i++) {
textContent = options[i].textContent || options[i].innerText;
if (textContent.indexOf(text) >= -1) {
return options[i].value;
}
}
return null;
}
var result = valueByText(document.getElementById('my_select'), 'Knowing_1');
var result = $('#my_select option:contains("Knowing_1")').val();