gpt4 book ai didi

javascript - selectedOptions.length 在 Internet Explorer 中不起作用,但在 Chrome 和 Firefox 中正常工作?

转载 作者:行者123 更新时间:2023-12-03 05:19:51 24 4
gpt4 key购买 nike

我一直在使用 ui.multiselect.js ,它与 HTML Select 类似:

我想要所选元素的长度。所以我使用了下面的代码:

var selectedOption =  document.getElementById('animalList').selectedOptions.length;

但似乎 selectedOptions.length 在 IE 中不起作用,但在 Chrome 和 Firefox 中正常工作

以下是我已经尝试过的替代方案:

var select = document.getElementById('animalList');
var len = select.options.length;

我得到的结果是0。

$("#animalList :selected").length;

我得到的结果是0。

最佳答案

要使用 multiselect 获取 select 元素的计数,请确保您的代码如下所示:

$(document).ready(function() {

$('button').click(function() {
// jquery version
var count = $("#foo :selected").length;
console.log("jQuery Count: " + count);

// pure javascript version
var options = document.getElementById('foo').options, count = 0;
for (var i=0; i < options.length; i++) {
if (options[i].selected) count++;
}
console.log("Pure Javascript: " + count);

});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Count Selected</button><br>
<select multiple id="foo">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>

我已经包含了纯 JavaScript 版本和 jQuery 版本,它们在您单击按钮时执行。

关于javascript - selectedOptions.length 在 Internet Explorer 中不起作用,但在 Chrome 和 Firefox 中正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41442558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com