After jQuery dynamically adds elements, the element registration event fails

Recently, Diu Jiang was learning jQuery, and encountered a problem while studying. Although it was finally solved, Diu Jiang felt that the solution to this problem should be recorded, so that other friends who encounter the same problem will not solve it like me. It's been a long time.
I will first post a piece of code with normal logic

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="jquery.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        a {
            text-decoration: none;
        }
        
        button {
            position: relative;
            left: 712px;
            top: 97px;
        }
        
        .content {
            width: 500px;
            height: 30px;
            line-height: 30px;
            border: 1px solid #bbb;
            margin: 100px auto;
            border-collapse: collapse;
        }
        
        th {
            background-color: rgb(27, 126, 184);
            color: #fff;
            border: 1px solid #bbb;
        }
        
        td {
            border: 1px solid #bbb;
        }
    </style>
</head>

<body>
    <button>添加数据</button>
    <table class="content" align="center">
        <tr>
            <th style="font-weight: 700;">课程名称</th>

            <th style="font-weight: 700;">所属学院</th>

            <th style="font-weight: 700;">已学会</th>
        </tr>

    </table>

    <script>
        $(function() {
            var t1 = $('<tr align="center"><td>javaScript</td><td>传智播客-前端与移动开发学院</td><td><a href="javascript:;" class="del">GET</a></td></tr>');
            var t2 = $('<tr align="center"><td>css</td><td>传智播客-前端与移动开发学院</td><td><a href="javascript:;">GET</a></td></tr>');
            var t3 = $('<tr align="center"><td>html</td><td>传智播客-前端与移动开发学院</td><td><a href="javascript:;">GET</a></td></tr>');
            var t4 = $('<tr align="center"><td>jQuery</td><td>传智播客-前端与移动开发学院</td><td><a href="javascript:;">GET</a></td></tr>');
            $('button').on('click', function() {
                // console.log($('table tr'));
                if ($('table tr').length === 1) {
                    $('table').append(t1);
                    console.log($(".del"));
                    // console.log($('table tr').length);
                } else if ($('table tr').length === 2) {
                    $('table').append(t2);
                } else if ($('table tr').length === 3) {
                    $('table').append(t3);
                } else if ($('table tr').length === 4) {
                    $('table').append(t4);
                } else {
                    return false;
                }
            });
            // $("table a").on('click', function() {
            //         $('table').children('tr').remove();
            //     })

            $('tr').on('click', 'a', function() {
                console.log(11);
                $(this).parents('tr').remove();
            })
        })
    </script>
</body>

</html>

Front-end page operation process:

1. First click the "Add Data" button to dynamically generate the a tag.

2. Click the a label (GET) again to view the console.

Result: nothing is output from the console

Because writing like this is problematic. All need to be modified. I will post my modified code first. explained later

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="jquery.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        a {
            text-decoration: none;
        }
        
        button {
            position: relative;
            left: 712px;
            top: 97px;
        }
        
        .content {
            width: 500px;
            height: 30px;
            line-height: 30px;
            border: 1px solid #bbb;
            margin: 100px auto;
            border-collapse: collapse;
        }
        
        th {
            background-color: rgb(27, 126, 184);
            color: #fff;
            border: 1px solid #bbb;
        }
        
        td {
            border: 1px solid #bbb;
        }
    </style>
</head>

<body>
    <button>添加数据</button>
    <table class="content" align="center">
        <tr>
            <th style="font-weight: 700;">课程名称</th>

            <th style="font-weight: 700;">所属学院</th>

            <th style="font-weight: 700;">已学会</th>
        </tr>

    </table>

    <script>
        $(function() {
            var t1 = $('<tr align="center"><td>javaScript</td><td>传智播客-前端与移动开发学院</td><td><a href="javascript:;" class="del">GET</a></td></tr>');
            var t2 = $('<tr align="center"><td>css</td><td>传智播客-前端与移动开发学院</td><td><a href="javascript:;">GET</a></td></tr>');
            var t3 = $('<tr align="center"><td>html</td><td>传智播客-前端与移动开发学院</td><td><a href="javascript:;">GET</a></td></tr>');
            var t4 = $('<tr align="center"><td>jQuery</td><td>传智播客-前端与移动开发学院</td><td><a href="javascript:;">GET</a></td></tr>');
            $('button').on('click', function() {
                // console.log($('table tr'));
                if ($('table tr').length === 1) {
                    $('table').append(t1);
                    console.log($(".del"));
                    // console.log($('table tr').length);
                } else if ($('table tr').length === 2) {
                    $('table').append(t2);
                } else if ($('table tr').length === 3) {
                    $('table').append(t3);
                } else if ($('table tr').length === 4) {
                    $('table').append(t4);
                } else {
                    return false;
                }
            });
            // $("table a").on('click', function() {
            //         $('table').children('tr').remove();
            //     })

            $('.content').on('click', 'a', function() {
                console.log(11);
                $(this).parents('tr').remove();
            })
        })
    </script>
</body>

</html>

Front-end page operation process:

1. First click the "Add Data" button to dynamically generate the a tag.

2. Click the a label (GET) again to view the console.

**Result: The console starts outputting**

Started to explain. In fact, you can see that there is only one difference here. I'm posting these two

// 控制台不输出
// 通过on事件委派来给tr里面的a标签添加点击事件
$('tr').on('click', 'a', function() {
    console.log(11);
    $(this).parents('tr').remove();
});
// 控制台输出
$('.content').on('click', 'a', function() {
    console.log(11);
    $(this).parents('tr').remove();
});

In the first one, we are event delegating a click event to the element of the a tag. But this kind of jquery can't get the dynamically added elements.

Program explanation:

Although on can bind events to elements dynamically created in the future, it must first obtain the parent element it already owns. Only then can dynamic elements be obtained.

That is to say, add an event to the parent element (the event type is the same as the event type that the dynamic element wants to implement)

So here you can get:

    <table class="content" align="center">
        <tr>
            <th style="font-weight: 700;">课程名称</th>

            <th style="font-weight: 700;">所属学院</th>

            <th style="font-weight: 700;">已学会</th>
        </tr>

// 动态添加的元素
        <tr align="center">
            <td>javaScript</td>

            <td>传智播客-前端与移动开发学院</td>
            
            <td><a href="javascript:;" class="del">GET</a></td>
        </tr>
    </table>

.content is the parent of the a tag

$('.content').on('click', 'a', function() {
    console.log(11);
    $(this).parents('tr').remove();
})

Just remember that in a dynamically generated element, its events cannot be specified directly. Only events of its parent tag can be filtered to specify specific element events.

There is another way of writing: directly specify the element event of dom. This is also possible.

$(document).on('click',"a",function(){
	console.log("22");
})

Guess you like

Origin blog.csdn.net/DIUDIUjiang/article/details/126284588