重置选择框的值 [英] Reset the Value of a Select Box

查看:99
本文介绍了重置选择框的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重置两个选择字段的值,结构如下:

I'm trying to reset the value of two select fields, structured like this,

<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做任何东西

Unfortunately, no matter how many ways I try it, it just doesn't happen. Nothing in the console. I have no idea what's going on? I know there has to be a way to do this, you can do anything with JS

编辑:

我发现问题只发生在我尝试在点击dom元素时触发代码时,但是,我知道代码应该正常工作,因为当我有

I figured out that the issue only occurs when I try to fire the code on the click of a dom element, however, I know that the code should be working, because when I have

$('p').click(function(){
  console.log('test');
});

它将'test'输出到控制台,但当我在此函数中包含代码时,没有任何反应。这是为什么?

It outputs 'test' to the console, but when I include the code in this function, nothing happens. Why is this?

推荐答案

我认为你只想重置一个元素。重置整个表单很简单:调用其重置方法。

I presume you only want to reset a single element. Resetting an entire form is simple: call its reset method.

重置select元素的最简单方法是设置其 selectedIndex 属性为默认值。如果您知道没有选项是默认选择选项,只需将选择元素 selectedIndex 属性设置为适当的值:

The easiest way to "reset" a select element is to set its selectedIndex property to the default value. If you know that no option is the default selected option, just set the select elemen'ts selectedIndex property to an appropriate value:

function resetSelectElement(selectElement) {
    selecElement.selectedIndex = 0;  // first option is selected, or
                                     // -1 for no option selected
}

但是,由于一个选项可能具有所选的属性或以其他方式设置为默认选择的选项,您可能需要这样做:

However, since one option may have the selected attribtue or otherwise be set to the default selected option, you may need to do:

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
}

并注意设置属性而不是属性,它们在不同的浏览器中有不同的效果。

And beware of setting attributes rather than properties, they have different effects in different browsers.

这篇关于重置选择框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆