One*_*ude 18 javascript jquery
我正在尝试重置两个选择字段的值,结构如下,
<select>
<option></option>
<option></option>
<option></option>
</select>
<select>
<option></option>
<option></option>
<option></option>
</select>
Run Code Online (Sandbox Code Playgroud)
jQuery的,
$('select').each(function(idx, sel) {
$(sel).find('option :eq(0)').attr('selected', true);
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,无论我尝试多少种方式,它都不会发生.控制台中没有任何内容.我不知道是怎么回事?我知道必须有一种方法可以做到这一点,你可以用JS 做任何事情
编辑:
我发现问题只发生在我尝试在点击dom元素时触发代码时,但是,我知道代码应该正常工作,因为当我有
$('p').click(function(){
console.log('test');
});
Run Code Online (Sandbox Code Playgroud)
它将'test'输出到控制台,但是当我在此函数中包含代码时,没有任何反应.为什么是这样?
Rob*_*obG 34
我认为你只想重置一个元素.重置整个表单很简单:调用其reset方法.
"重置"select元素的最简单方法是将其selectedIndex属性设置为默认值.如果您知道没有选项是默认选择的选项,只需将select elemen'ts selectedIndex属性设置为适当的值:
function resetSelectElement(selectElement) {
selecElement.selectedIndex = 0; // first option is selected, or
// -1 for no option selected
}
Run Code Online (Sandbox Code Playgroud)
但是,由于一个选项可能具有所选的属性或以其他方式设置为默认选择的选项,您可能需要执行以下操作:
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
}
Run Code Online (Sandbox Code Playgroud)
并且要注意设置属性而不是属性,它们在不同的浏览器中具有不同的效果.
继@ RobG的纯/ vanilla javascript答案,你可以重置为'默认'值
selectElement.selectedIndex = null;
Run Code Online (Sandbox Code Playgroud)
似乎-1取消选择所有项目,null选择默认项目,0或正数选择相应的索引选项.
select对象中的选项按照它们的定义顺序编制索引,从索引0开始.
neRok在上面提到了这个答案,我只是在扩展它。
根据稍微过时但方便的 O'Reilly 参考书Javascript: The Definitive Guide:
Select 对象的selectedIndex属性是一个整数,用于指定 Select 对象中所选选项的索引。如果未选择任何选项,则selectedIndex为 -1。
因此,以下 javascript 代码会将 Select 对象“重置”为未选择任何选项:
select_box = document.getElementById("myselectbox");
select_box.selectedIndex = -1;
Run Code Online (Sandbox Code Playgroud)
请注意,以这种方式更改选择不会触发onchange()事件处理程序。
| 归档时间: |
|
| 查看次数: |
86690 次 |
| 最近记录: |