小练习2

1 可以对列表增加一行,删除一行

image.png

代码块
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<button id="b1">添加</button>
<table border="1">
    <thead>
    <tr>
        <th>序号</th>
        <th>姓名</th>
        <th>爱好</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>1</td>
        <td>康抻</td>
        <td>gay in gay out</td>
        <td><button class="delete">开除</button></td>
    </tr>
    <tr>
        <td>2</td>
        <td>蝇蝇</td>
        <td>用手</td>
        <td><button class="delete">开除</button></td>
    </tr>
    </tbody>
</table>
<script src='jquery-3.4.1.min.js'></script>



<script>
    $("#b1").click(function () {
        // 在表格的最后添加一行数据
        // 1. 先有数据
        var trEle = document.createElement("tr");  // trEle是一个DOM对象
        trEle.innerHTML = `
            <td>3</td>
            <td>黄袍哥</td>
            <td>吹牛逼</td>
            <td><button class="delete">开除</button></td>
        `;
        // 2. 追加到tbody的最后
        $("tbody").append(trEle);
    });
	

    // 使用事件委托的方式给未来的标签绑定事件
    $("tbody").on("click", ".delete", function () {
        // this指的就是谁触发的事件,this是一个DOM对象,$(this)是jQuery对象
        console.log(this);
        <!--$(this).parent().parent().remove();-->
		$(this).parentsUntil('tbody').remove();
    })
</script>
</body>
</html>

2 .stopPropagation()阻止冒泡向父层传播

<div id="d1">
    <p id="p1">
        <span id="s1">span</span>
    </p>
</div>

我是分割线

$("#s1").click(function (event) {
        // event表示事件本身
        alert("这是span标签");
        // 阻止事件冒泡
        event.stopPropagation()
    });
    $("#p1").click(function () {
        alert("这是p标签")
    });
    $("#d1").click(function () {
        alert("这是div标签")
    });

3 判断text文本框输入值,如果为空,阻止默认事件发生,否则按照代码来执行

image.png

代码块
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>


<hr>
<form action="">
    <input type="text" id="i1">
    <input type="submit" value="提交" id="i2">
</form>

<script src='jquery-3.4.1.min.js'></script>
<script>
    

    // 点击submit按钮,先校验input框的值为不为空,
    // 为空就不提交,不提交就不刷新,不为空就提交,sumbit标签提交的时候默认刷新
     $("#i2").click(function (event) {
        alert("这是form表单的提交按钮!");
        var value = $("#i1").val();
        if (value.length === 0){
            // 为空就不提交
            // 不执行后续默认的提交事件
            // 阻止默认事件的执行
            // event.preventDefault() 表示默认的事件不执行了。
            return false; <!--表示后面都不走了-->
        }
    });
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/hellosiyu/p/12490017.html