我遇到了同样的问题,其他答案都不适合我。这是我发现有效的解决方案:
$(document).ready(function(){
$("#example").change(function(){
var options = document.getElementById("example").options;
var selectedIndex = document.getElementById("example").selectedIndex;
var selectedOptionText = options[selectedIndex].text;
var selectedOptionValue = options[selectedIndex].value;
console.log("Id of selected option is: " + selectedOptionValue);
console.log("Text of selected option is: " + selectedOptionText);
});
});
为了进一步理解这个问题,考虑一下在处理 JSP 时会创建什么 HTML 是有帮助的。将<s:select>生成以下 HTML:
<select id="example" name="example">
<option value="456">TextA</option>
...
</select>
按照 OP 的示例代码,“456”将exampleKey来自exampleValue. <option>中的每个项目都会有这样的 HTML exampleList。
请注意,在我的解决方案中,我使用了 jQuery.change()函数。但是,我也尝试了解决方案onchange="fun()",就像 OP 所做的那样,这也有效。
当我尝试用 替换document.getElementById("example")时$("#example"),解决方案不起作用。
阅读有关选项 selectedValue 的参考资料也很有帮助。<select>