jQuery之遍歷索引相關方法(each、index)

文章目錄

each

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>溫故而知"心"</title>
</head>

<body>
    <ul>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</body>

<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script>
    /*
    給ul裏面的li依次添加序號(1、2、3...)
    */
    // $('li')
    //     .text(function () { })
    //     .addClass(function () { })

    $('li').each(function (index, ele) {
        $(ele).text(index + 1).addClass('demo' + index)
    })
</script>

</html>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>溫故而知"心"</title>
</head>

<body>
    <p>
        <i></i>
        <span></span>
        <i></i>
        <span></span>
    </p>
</body>

<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script>
    //將each和children配合一起使用
    $('p').children().each(function (index, ele) {
        if (ele.nodeName == "I") {
            $(ele).text(`i-${index}`)
        } else {
            $(ele).text(`span-${index}`)
        }
    })
</script>

</html>

index

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>溫故而知"心"</title>
</head>

<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
    </ul>
</body>

<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script>
    //點擊ul裏面的li,獲取li的下標值
    $('ul').on('click', 'li', function (e) {
        console.log($(e.target).index())
    })
</script>

</html>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>溫故而知"心"</title>
</head>

<body>
    <p>
        <i>1</i>
        <span>2</span>
        <i>3</i>
        <span>4</span>
    </p>

</body>

<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script>
    //給index加參數,點擊任意的span標籤,得到該標籤在兄弟元素span中的下標值
    $('p').children().on('click', function (e) {
        console.log($('p span').index($(e.target)))
    })
</script>

</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章