一步一步学jQuery(四)

这篇博客,总结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';
    });  
})
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值