为什么我们写.attr('selected','selected')
与选择标签jQuery的 - 为什么我们写.attr(“选择”,“选择”)与选择标签
对于前:
$('#countryList option').filter(function() {
return ($(this).text() == findText); }).attr('selected','selected');
});
这是什么真正的意思?
为什么我们写.attr('selected','selected')
与选择标签jQuery的 - 为什么我们写.attr(“选择”,“选择”)与选择标签
对于前:
$('#countryList option').filter(function() {
return ($(this).text() == findText); }).attr('selected','selected');
});
这是什么真正的意思?
.attr('selected','selected')
的说明。
内.attr
第一个参数表示要在第二个同时参数设置这是作为第一个参数传递属性的value
指向attribute
。
如果我们刚刚.attr('selected')
那么它只是返回值selected
属性。
为什么我们写.attr(“选择”,“选择”)
这就是jQuery的允许选择,如果你想设置选择,你可以使用val的选择项( ),以所选择的选项
$('#countryList').val(5); // it will set the selected attribute for option having value 5
没有得到它.... PLZ详细说明。 –
.attr()
jquery的方法被用于设置所述选择的属性设置。 所以在你的情况下,这个功能是用来显示文本作为一个选定的下拉菜单。
一般而言,大多数浏览器仅仅通过它的存在/不存在而不考虑它的值来选择属性。根据规范,这是一个布尔属性(当通过javascript设置时),但在HTML标记中,该属性通常由它的存在/缺失来表示。这意味着该元素默认为下拉菜单中可见的选项。
看看是怎么回事:
$('#countryList option').filter(function() {
return ($(this).text() == findText);
}).attr('selected','selected');
}); //<---------this is extra
不错,但问题是,为什么我们写.attr('selected','selected')
与select
标签:
如果你能看到你没有选择的属性设置为<select>
但<option>
它包含。
您的代码将设置所选择的属性对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做同样的事情。
这更多的是布尔属性的约定;要么是空的,要么它包含与属性名称本身相同的值。 –