本文介绍了getElementsByClassName()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的代码是按字母顺序对表单列表选项进行排序,但是'getElementsByClassName()'不起作用,我不知道为什么.
The follwing code is to sort form list options alphabetically but the 'getElementsByClassName()' is not working and I cant figure out why.
我正在使用最新的jQuery.
I am using the latest jQuery.
window.onload=function(){
function sortlist() {
var cl = document.getElementsByClassName('car_options');
var clTexts = new Array();
for(i = 1; i < cl.length; i++) {
clTexts[i-1] =
cl.options[i].text.toUpperCase() + "," +
cl.options[i].text + "," +
cl.options[i].value;
}
clTexts.sort();
for(i = 1; i < cl.length; i++) {
var parts = clTexts[i-1].split(',');
cl.options[i].text = parts[1];
cl.options[i].value = parts[2];
}
sortlist();
}
在正文部分
<form action="" method="get">
<p><label for="car_make"></label>
<select id="car_make" class="car_options" name="car_make">
<option value="">By Make</option>
<option value="Vauxhall">Vauxhall</option>
<option value="BMW">BMW</option>
<option value="Toyota">Toyota</option>
<option value="Lexus">Lexus</option>
<option value="Audi">Audi</option>
<option value="Ford">Ford</option>
</select>
<label for="car_color"></label>
<select name="car_color" id="car_color" class="car_options">
<option value="">By Color</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Black">Black</option>
<option value="Grey">Grey</option>
</select>
<input type="submit" name="search" id="search" value="Search">
</form>
推荐答案
使用document.getElementsByClassName('car_options')[0]
getElementsByClassName
返回一组元素具有所有给定的类名.
getElementsByClassName
returns a set of elements which have all the given class names.
如果您有多个元素,那么我们必须对其进行迭代.喜欢
If you have multiple elements then we have to iterate it through. like
var elements = document.getElementsByClassName('car_options');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', function() {
}, false);
}
注意:在IE中, IE9 +
更新代码
function sortlist() {
var elements = document.getElementsByClassName('car_options');
for (var j = 0; j < elements.length; j++) {
var cl = elements[j];
var clTexts = new Array();
for (i = 1; i < cl.options.length; i++) {
clTexts[i - 1] = cl.options[i].text.toUpperCase() + "," + cl.options[i].text + "," + cl.options[i].value;
}
clTexts.sort();
for (i = 1; i < cl.options.length; i++) {
var parts = clTexts[i - 1].split(',');
cl.options[i].text = parts[1];
cl.options[i].value = parts[2];
}
}
}
这篇关于getElementsByClassName()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!