这篇博客,总结jQuery对DOM的基本操作。
1. 回顾DOM
D代表document,O代表object,M代表model。即文档上的元素或者文本。操作的对象也即元素或文档。
2. 设置元素及内容
$(function(){
alert($("#box").html()); //获取元素,html的值
$("#box").html("<em>长城</em>"); //设置元素,html的值
alert($('#box').text()); //获取元素,文本的值
$('#box').text("烽火"); //设置元素,文本的值
alert($('input').val()); //获取表单元素的值
$('input').val("白烟"); //设置表单元素的值
$('#box').text(function(index,value){ //元素的值,追加
return $(this).text() + "welcome to BeiJing!"
});
$('input').val(['男','女','编程']); //多个表单元素,选中状态
})
3.元素属性操作
$(function(){
alert($('#box').attr('title')); //获取元素,属性的值
$('#box').attr('title','clap'); //修改元素,属性值
$('#box').attr('title', function(index, value){ //设置元素属性,追加
return value + 'here';
});
$('#box').removeAttr('title'); //移除元素属性
}
4.元素样式操作
$(function(){
alert($('#box').css('height')); //获取元素,高度
$('#box').css('color','green'); //设置元素,颜色
var box = $('#box').css(['width','height','color']);
$.each(box,function(attr,value){ //对象数组,遍历
alert(attr + ": " + value);
})
$('div').each(function(index,value){ //jQuery对象
alert(index + ": " + value);
})
$('#box').css({ //设置多个样式
'background': 'yellow',
'color': 'green',
'font-size': '20px'
})
$('#box').css('width',function(index, value){ //设置元素属性,需要计算
return parseInt(value) - 600 + 'px';
})
$('#box').addClass('item'); //元素,添加类
$('#box').removeClass('item') //元素,移除类
$('#box').click(function(){ //单击div,两个样式之间切换
$(this).toggleClass(function(){
if($(this).hasClass('red')){
$(this).removeClass('red');
return 'green';
}else{
$(this).removeClass('green');
return 'red';
}
});
})
var count =0;
$('#box').click(function(){ //根据条件,变换div的样式
$(this).toggleClass(function(index, className, switchBool){
alert(index + "," + className + "," + switchBool);
return $(this).hasClass('red')?'green':'red';
},count++%3 ==0);
})
})
5.CSS方法
$(function(){
alert($('#box').width()); //CSS方法,width()
$('#box').width(500); //设置元素的长度
$('#box').width('600px'); //设置元素的长度
$('#box').width(function(index, value){ //设置元素的长度
return value-700 + 'px';
});
})