为什么我们.attr('selected','selected')用选择标签写
例如:
$('#countryList option').filter(function () {
return ($(this).text() == findText); }).attr('selected','selected');
});
它的真正含义是什么?
的解释 .attr('selected','selected')。
里面的第一个参数.attr表示attribute您要指向value的属性,而第二个参数集作为第一个参数传递。
如果我们有.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 方法用于设置选择器的属性。因此,在您的情况下,此功能用于将文本显示为下拉列表中的选定内容。
通常,大多数浏览器都会尊重 selected 属性,因为它的存在/不存在而不管其值如何。根据规范,这是一个布尔属性(通过 javascript 设置时),但在 HTML 标记中,此属性通常由其存在/不存在表示。这意味着该元素默认是下拉菜单中可见的选项。
看看发生了什么:
$('#countryList option').filter(function () {
return ($(this).text() == findText);
}).attr('selected','selected');
}); //<---------this is extra
好的,但问题是我们为什么要写标签.attr('selected','selected')select:
如果您可以看到您没有将选定的属性设置为<select>但<option>它包含。
您的代码会将 selected 属性设置为option包含文本的属性,该属性相当于findText
selected是 的布尔属性<option>;以 HTML 属性表示,它的值要么为空(或未指定),要么等于属性名称本身来指示true(按照约定)。
$('#countryList option').filter(function () {
return ($(this).text() == findText);
}).attr('selected','selected');
该代码selected为第一个匹配的选项元素设置属性。代码实际上有几个问题:
.attr()函数。selected属性严格来说不是属性而是属性。可以这样重写:
$('#countryList option').each(function () {
if (this.text == findText) {
this.selected = true;
return false; // stop searching after we find the first match
}
});
在任何编程语言中,当您想要设置属性时,您必须分配一个引用该属性的值。所以 jquery 做同样的事情。