Day 56 jquery

An example of event delegation

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Event delegation example</title>
</head>
<body>

<input type="button" value="添加新数据" id="add">
<table border="1">
    <thead>
    <tr>
        <th>#</th>
        <th>Name</th>
        <th>Action</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>1</td>
        <td>Boss Kim</td>
        <td><input type="button" value="删除" class="delete"></td>
    </tr>
    <tr>
        <td>2</td>
        <td>Goddess of View</td>
        <td><input type="button" value="删除" class="delete"></td>
    </tr>
    <tr>
        <td>3</td>
        <td>The Pharaoh Next Door</td>
        <td><input type="button" value="删除" class="delete"></td>
    </tr>
    </tbody>
</table>


<script src="jquery-3.3.1.js"></script>

<script>
    // Click the add button to add a new data
     // 1. Find the button binding click event 
    $( " #add " ).on( " click " , function () {
         // What to do when the add button is clicked
         // 1. Create a new tr 
        var trEle = document.createElement( " tr " );
        trEle.innerHTML = ' <td>4</td> <td>Nezha</td> <td><input type="button" value="delete" class="delete"></td> ' ;
         / / 2. Append the created tr to tbody 
        $( " tbody " ).append(trEle);
    });

    // Click the delete button of each row to delete the current row
     // 1. Find the delete button of each row and bind the click event 
    $( " table " ).on( " click " , " input.delete " , function ( ) {
         // Bind an event to the table tag, and listen to the tag with delete style class in my descendants. If it is clicked, I will do the following things
         // What to do when the delete button of each row is clicked //
         1. Delete this line of the currently clicked button 
        console.log( this );
        $(this).parent().parent().remove();
    })
</script>
</body>
</html>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324771917&siteId=291194637
#56