我正在尝试重置两个选择字段的值,其结构如下,
<select>
<option></option>
<option></option>
<option></option>
</select>
<select>
<option></option>
<option></option>
<option></option>
</select>
jQuery,
$('select').each(function(idx, sel) {
$(sel).find('option :eq(0)').attr('selected', true);
});
不幸的是,无论我尝试多少种方法,它都不会发生。控制台中什么也没有。我不知道发生了什么事?我知道必须有一种方法可以做到这一点,你可以做到anything with JS
EDIT:
我发现这个问题只发生在我尝试点击 dom 元素时触发代码时,但是,我知道代码应该可以工作,因为当我
$('p').click(function(){
console.log('test');
});
它将“测试”输出到控制台,但是当我在此函数中包含代码时,什么也没有发生。为什么是这样?
我假设您只想重置单个元素。重置整个表单很简单:调用它reset method.
“重置”选择元素的最简单方法是设置其selectedIndex
属性设置为默认值。如果您知道没有选项是默认选择的选项,只需设置选择元素选定索引属性到适当的值:
function resetSelectElement(selectElement) {
selecElement.selectedIndex = 0; // first option is selected, or
// -1 for no option selected
}
但是,由于一个选项可能具有选定的属性或以其他方式设置为默认选定的选项,因此您可能需要执行以下操作:
function resetSelectElement(selectElement) {
var options = selectElement.options;
// Look for a default selected option
for (var i=0, iLen=options.length; i<iLen; i++) {
if (options[i].defaultSelected) {
selectElement.selectedIndex = i;
return;
}
}
// If no option is the default, select first or none as appropriate
selectElement.selectedIndex = 0; // or -1 for no option selected
}
并且要注意设置属性而不是属性,它们在不同的浏览器中具有不同的效果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)