【问题标题】:jquery - Why do we write .attr('selected','selected') with select tagjquery - 为什么我们用选择标签写 .attr('selected','selected')
【发布时间】:2013-04-01 09:36:08
【问题描述】:

为什么我们用选择标签写.attr('selected','selected')

例如:

$('#countryList option').filter(function () {
 return ($(this).text() == findText); }).attr('selected','selected');
});

它的真正含义是什么?

【问题讨论】:

  • 这更像是布尔属性的约定;它要么是空的,要么包含与属性名称本身相同的值。

标签: jquery select attr selected


【解决方案1】:

.attr('selected','selected')的解释。

.attr 中的第一个参数表示您要指向的attribute,而第二个参数设置value 作为第一个参数传递的属性。

如果我们只有.attr('selected'),那么它只返回selected 属性的值。

【讨论】:

    【解决方案2】:

    .attr()jquery方法用于设置选择器的属性。 因此,在您的情况下,此功能用于将文本显示为下拉列表中的选定内容。

    See tutorial here.

    【讨论】:

      【解决方案3】:

      一般来说,大多数浏览器都会尊重 selected 属性,因为它只是存在/不存在,而与它的值无关。根据规范,这是一个布尔属性(通过 javascript 设置时),但在 HTML 标记中,此属性通常由其存在/不存在表示。这意味着该元素默认是下拉菜单中可见的选项。

      【讨论】:

        【解决方案4】:

        我们为什么要写.attr('selected','selected')

        这就是jQuery允许选择的方式,如果你想设置select的选中项可以使用val()来设置选中的选项

        $('#countryList').val(5); // it will set the selected attribute for option having value 5
        

        【讨论】:

          【解决方案5】:

          看看发生了什么:

          $('#countryList option').filter(function () {
             return ($(this).text() == findText); 
          }).attr('selected','selected');
          }); //<---------this is extra
          

          好的,但问题是我们为什么要写.attr('selected','selected')select 标签

          如果您可以看到您没有将所选属性设置为 &lt;select&gt; 而是 &lt;option&gt; 它包含。

          您的代码会将 selected 属性设置为 option,其中包含等同于 findText 的文本

          【讨论】:

            【解决方案6】:

            selected&lt;option&gt; 的布尔属性;以 HTML 属性表示,其值为空(或未指定)或等于属性名称本身以指示 true(按约定)。

            $('#countryList option').filter(function () {
               return ($(this).text() == findText); 
            }).attr('selected','selected');
            

            该代码为第一个匹配的选项元素设置selected 属性。代码其实有几个问题:

            1. 无论过滤结果如何,都会调用 .attr() 函数。
            2. selected 属性严格来说不是属性,而是属性。

            可以这样改写:

            $('#countryList option').each(function () {
                if (this.text == findText) {
                    this.selected = true;
                    return false; // stop searching after we find the first match
                }
            });
            

            【讨论】:

              【解决方案7】:

              在任何编程语言中,当您想要设置属性时,您必须分配一个引用该属性的值。所以 jquery 做同样的事情。

              【讨论】:

                猜你喜欢
                • 2013-10-09
                • 2017-05-09
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2012-09-28
                相关资源
                最近更新 更多