jQuery基本操作

2018-08-28  本文已影响0人  奔跑的老少年

1、文本操作:

     $(..).text() ------获取文本内容
     $(..).text(‘<a>hhhhh</a>’) ------设置文本内容
     $(..).html() ------获取文本内容
     $(..).html(‘<a>hhhhh</a>’) ------设置文本内容
     $(..).val() ------获取value值
     $(..).val(..) ------设置value值 

2、样式操作:
addClass
removeClass
toggleClass
例如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hide{
            display: none;
        }
    </style>
</head>
<body>
<input type="button" id="i1" value="开关">
<div class="c1">jdfjgfdgdf</div>
<script src="jquery-3.3.1.js"></script>
<script>
    $('#i1').click(function () {
        // if($('.c1').hasClass('hide')){
        //     $('.c1').removeClass('hide');
        // }else{
        //     $('.c1').addClass('hide');
        // }
        //toggleClass就相当于以上的if语句
        $('.c1').toggleClass('hide')
    })
</script>
</body>
</html>

3、属性操作:

    专门用于做自定义属性:
    $(..).attr(‘n’)  ----获取属性n的值
    $(..).attr('n','v')----设置属性n的值
    $(..).removeAttr('n','v')

    专门用于checkbox、radio
    $(..).prop('checked')--获取选中状态
    $(..).prop('checked','ture')--设置选中状态

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<input type="button" value="全选" onclick="checkAll();">
<input type="button" value="反选" onclick="reverseAll();">
<input type="button" value="取消" onclick="cancelAll();">

<table border="1">
    <thead></thead>
    <tr>
        <th>选项</th>
        <th>ip</th>
        <th>port</th>
    </tr>
    <tbody id="tb">
    <tr>
        <td><input type="checkbox"></td>
        <td>1.1.1</td>
        <td>80</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>1.1.1</td>
        <td>80</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>1.1.1</td>
        <td>80</td>
    </tr>
   
    </tbody>
</table>
<script src="jquery-3.3.1.js"></script>
<script>
    function checkAll() {
        //prop('checked',true)设置选中状态
        $(':checkbox').prop('checked',true);
    }
    function cancelAll() {
        $(':checkbox').prop('checked',false);
    }
    function reverseAll() {
        $(':checkbox').each(function(){
            // 方法一:
            // if(this.checked){
            //     this.checked = false;
            // }else {
            //     this.checked = true;
            // }


            //方法二:
            //prop('checked')获取选中状态
            // if($(this).prop('checked')){
            //     $(this).prop('checked',false)
            // }else {
            //      $(this).prop('checked',true)
            // }

            //方法三:
            var v= $(this).prop('checked')?false:true
            $(this).prop('checked',v)

        })
    }
</script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读