jquery-为什么要用select标记编写.attr(';selected';,';selected';)

jquery-为什么要用select标记编写.attr(';selected';,';selected';),jquery,select,attr,selected,Jquery,Select,Attr,Selected,为什么我们要用select标记编写.attr('selected','selected') 例如: $('#countryList option').filter(function () { return ($(this).text() == findText); }).attr('selected','selected'); }); 这到底意味着什么 为什么我们要写.attr('selected','selected') 这就是jQuery允许选择的方式,如果要设置select的选定项,可

为什么我们要用select标记编写
.attr('selected','selected')

例如:

$('#countryList option').filter(function () {
 return ($(this).text() == findText); }).attr('selected','selected');
});
这到底意味着什么

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

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

$('#countryList').val(5); // it will set the selected attribute for option having value 5
.attr()
jquery方法用于设置选择器的属性。 因此,在您的情况下,此函数用于将文本显示为选中的下拉列表


.

一般来说,大多数浏览器都会尊重所选属性的存在/不存在,而不考虑其值。根据规范,这是一个布尔属性(当通过javascript设置时),但在HTML标记中,该属性通常由其存在/不存在来表示。这意味着默认情况下,元素是下拉列表中可见的选项。

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

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

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

查看发生了什么:

$('#countryList option').filter(function () {
   return ($(this).text() == findText); 
}).attr('selected','selected');
}); //<---------this is extra
$(“#国家列表选项”).filter(函数(){
返回($(this).text()==findText);
}).attr('selected','selected');

}); // 所选的
的布尔属性;以HTML属性表示,其值要么为空(或未指定),要么等于属性名称本身,以表示
true
(按惯例)

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

  • 无论筛选结果如何,都会调用
    .attr()
    函数
  • 所选的
    属性严格来说不是属性,而是属性
  • 可以这样重写:

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

    在任何编程语言中,当您要设置属性时,必须指定一个引用该属性的值。因此jquery也做了同样的事情。

    它更像是布尔属性的约定;它要么为空,要么包含与属性名称本身相同的值。
    $('#countryList option').each(function () {
        if (this.text == findText) {
            this.selected = true;
            return false; // stop searching after we find the first match
        }
    });