我正在尝试重置两个选择字段的值,其结构如下,
<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);
});
不幸的是,无论我尝试多少种方法,它都不会发生。控制台中什么也没有。我不知道发生了什么事?我知道必须有一种方法可以做到这一点,你可以用 JS 做任何事情
编辑:
我发现这个问题只发生在我尝试点击 dom 元素时触发代码时,但是,我知道代码应该可以工作,因为当我有
$('p').click(function(){
console.log('test');
});
它将“测试”输出到控制台,但是当我在此函数中包含代码时,什么也没有发生。这是为什么?
最佳答案
我认为您只想重置单个元素。重置整个表单很简单:调用其reset方法。
“重置”选择元素的最简单方法是将其 selectedIndex
属性设置为默认值。如果您知道没有选项是默认选择的选项,只需将选择元素的 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
}
并且要注意设置属性而不是属性,它们在不同的浏览器中具有不同的效果。
关于javascript - 重置选择框的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12737528/