JQuery学习笔记八
学习笔记
removeClass([class|fn]) 返回值:jQuery
从所有匹配的元素中删除全部或者指定的类。
classStringV1.0
一个或多个要删除的CSS类名,请用空格分开
function(index, class)FunctionV1.4
此函数必须返回一个或多个空格分隔的class名。接受两个参数,index参数为对象在这个集合中的索引值,class参数为这个对象原先的class属性值。
从匹配的元素中删除 'selected' 类
$("p").removeClass("selected");
删除匹配元素的所有类
$("p").removeClass();
删除最后一个元素上与前面重复的class
$('li:last').removeClass(function() {
return $(this).prev().attr('class');
});
toggleClass(class|fn[,sw]) 返回值:jQuery
如果存在(不存在)就删除(添加)一个类。
classStringV1.0
CSS类名
class,switchString,BooleanV1.3
1:要切换的CSS类名.
2:用于决定元素是否包含class的布尔值。
switchBooleanV1.4
用于决定元素是否包含class的布尔值。
function(index, class,switch)[, switch] Function,BooleanV1.4
1:用来返回在匹配的元素集合中的每个元素上用来切换的样式类名的一个函数。接收元素的索引位置和元素旧的样式类作为参数。
2: 一个用来判断样式类添加还是移除的 boolean 值。
为匹配的元素切换 'selected' 类
$("p").toggleClass("selected");
参数class,switch 描述:
每点击三下加上一次 'highlight' 类
<strong>jQuery 代码:</strong>
var count = 0;
$("p").click(function(){
$(this).toggleClass("highlight", count++ % 3 == 0);
});
根据父元素来设置class属性
$('div.foo').toggleClass(function() {
if ($(this).parent().is('.bar') {
return 'happy';
} else {
return 'sad';
}
});
html([val|fn]) 返回值:String
取得第一个匹配元素的html内容。这个函数不能用于XML文档。但可以用于XHTML文档。
在一个 HTML 文档中, 我们可以使用 .html() 方法来获取任意一个元素的内容。 如果选择器匹配多于一个的元素,那么只有第一个匹配元素的 HTML 内容会被获取。
valStringV1.0
用于设定HTML内容的值
function(index, html)FunctionV1.4
此函数返回一个HTML字符串。接受两个参数,index为元素在集合中的索引位置,html为原先的HTML值。
返回p元素的内容。
$('p').html();
设置所有 p 元素的内容
$("p").html("Hello <b>world</b>!");
回调函数描述:
使用函数来设置所有匹配元素的内容。
$("p").html(function(n){
return "这个 p 元素的 index 是:" + n;
});
text([val|fn]) 返回值:String
取得所有匹配元素的内容。
结果是由所有匹配元素包含的文本内容组合起来的文本。这个方法对HTML和XML文档都有效。
valStringV1.0
用于设置元素内容的文本
function(index, text)FunctionV1.4
此函数返回一个字符串。接受两个参数,index为元素在集合中的索引位置,text为原先的text值。
返回p元素的文本内容。
$('p').text();
设置所有 p 元素的文本内容
$("p").text("Hello world!");
使用函数来设置所有匹配元素的文本内容。
$("p").text(function(n){
return "这个 p 元素的 index 是:" + n;
});
val([val|fn|arr]) 返回值:String,Array
获得匹配元素的当前值。
在 jQuery 1.2 中,可以返回任意元素的值了。包括select。如果多选,将返回一个数组,其包含所选的值。
valStringV1.0
要设置的值。
function(index, value)FunctionV1.4
此函数返回一个要设置的值。接受两个参数,index为元素在集合中的索引位置,text为原先的text值。
arrayArray<String>V1.0
用于 check/select 的值
无参数 描述:
获取文本框中的值
$("input").val();
参数val 描述:
设定文本框的值
$("input").val("hello world!");
设定文本框的值
$('input:text.items').val(function() {
return this.value + ' ' + this.className;
});
参数array 描述:
设定一个select和一个多选的select的值
<select id="single">
<option>Single</option>
<option>Single2</option>
</select>
<select id="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select><br/>
<input type="checkbox" value="check1"/> check1
<input type="checkbox" value="check2"/> check2
<input type="radio" value="radio1"/> radio1
<input type="radio" value="radio2"/> radio2
$("#single").val("Single2");
$("#multiple").val(["Multiple2", "Multiple3"]);
$("input").val(["check2", "radio1"]);