在javascript中通过值NOT INDEX获取所选选项的内部html

Get inner html of the selected option by value NOT INDEX in javascript

本文关键字:选项 html 内部 获取 INDEX javascript NOT      更新时间:2023-09-26

我有HTML代码

<select id="city">
<option value="A">Mumbai</option> 
<option value="B">Bangalore</option> 
<option value="C">Delhi</option> 
<option value="D">Indore</option> 
</select>

我想要一个JavaScript,用于通过其值获取选项的innerHTML

我试过了

var selectedValue = document.getElementById('city').value;
var city = document.querySelector('#city option[value='+selectedValue+']').innerHTML;
alert(city);

但是给出错误

语法错误: 指定了无效或非法的字符串

您可以将querySelector方法与[value=A]选择器一起使用:

var city = document.querySelector('#city option[value=A]').innerHTML

JSFiddle

不知道为什么你可能想这样做。纽威斯,这里是:

<select id="city">
<option value="A">Mumbai</option> 
<option value="B">Bangalore</option> 
<option value="C">Delhi</option> 
<option value="D">Indore</option> 
</select>
<script>
    var city = (document.getElementById('city').innerHTML).split('</option>');
    console.log(GetOptionHtml_ByValue('city', 'B'));
function GetOptionHtml_ByValue(xElementId, xValue) {
    AllHtml = (document.getElementById('city').innerHTML).split('</option>');
Array1 = [];
Array2 = [];
Array3 = [];
Array4  = [];
FoundIndex = -1;
for (i = 0; i < AllHtml.length; i++) {
    str = AllHtml[i];
    Array1 = str.split('<option value="');
    for (j = 0; j < Array1.length; j++) { 
        str2 = Array1[j];
        Array2 = str2.split('">');
            for (k = 0; k < Array2.length; k++) { 
                str3 = Array2[k];
                if ((j==1) && (k==0)) {
                        Array3.push(str3);
                        if (str3 == xValue) FoundIndex = Array3.length -1;
                    }
                if ((j==1) && (k==1))
                    Array4.push(str3);
            }
    }
}
if (FoundIndex > -1) 
    returnme = Array4[FoundIndex];
else
    returnme = 'NOT_FOUND';
return returnme;
}
</script>

只需使用 options 属性获取所有可用选项,使用 selectedIndex 属性即可知道选择了哪一个选项,并使用所选选项的 innerHTML 属性。

var cityElem = document.getElementById('city');
var selectedIndex = cityElem.selectedIndex;
if(selectedIndex != -1) {
    var selectedOption = cityElem.options[selectedIndex];
    var optionInnerHtml = selectedOption.innerHTML;
    alert(optionInnerHtml);
}

请注意,如果您将 HTML 放在选项元素中,它将忽略 HTML 标签,而只是将文本连接在一起。这必须在 HTML 处理的早期阶段完成,因为当您访问 javascript 中的值时,您只是在访问文本。如果这足够好,那么这个解决方案将起作用,否则你将不得不手动解析select元素的内部html。

嘟嘟...