jQuery on 方法对于网页元素动态绑定好处

问题描述:

有的时候我们需要在网页上动态的添加一些网页元素,这个时候如果我们之前写的js不高明,那么这些新天加的元素将不能够绑定那个已有的js事件:

代码示例:

<!Doctype html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Test for JQ on function</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
</head>
<body>
    <table border="1px">
        <thead>
            <tr>
                <th>列1</th>
                <th>列2</th>
            </tr>
        </thead>
        <tbody id="tbody1">
            <tr>
                <td class="child">1.1</td>
                <td class="child">2.1</td>
            </tr>
        </tbody>
    </table>
    <p>button的功能是添加新的一行。</p>
    <input type="button" value="button" id="funButton">
<script>

$("#funButton").click(function(){
    var trLeng = $("#tbody1").children("tr").length;
    trLeng = trLeng -1;
    $("#tbody1").children("tr").eq(trLeng).after("<tr><td class='child'>2.1</td><td class='child'>2.2</td></tr>");
});
$(".child").click(function(){
    alert($(this).text());
});
</script>
</body>
</html>
js功能描述:

最开始的table是有click事件绑定的,但是如果点击了button添加了新的行,那么新添加的行将不会有click事件触发。所以我们需要改进使用jquery 的on 方法。

修改后的代码:

<!Doctype html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Test for JQ on function</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
</head>
<body>
	<table border="1px">
		<thead>
			<tr>
				<th>列1</th>
				<th>列2</th>
			</tr>
		</thead>
		<tbody id="tbody1">
			<tr>
				<td class="child">1.1</td>
				<td class="child">2.1</td>
			</tr>
		</tbody>
	</table>
	<p>button的功能是添加新的一行。</p>
	<input type="button" value="button" id="funButton">
<script>

$("#funButton").click(function(){
	var trLeng = $("#tbody1").children("tr").length;
	trLeng = trLeng -1;
	$("#tbody1").children("tr").eq(trLeng).after("<tr><td class='child'>2.1</td><td class='child'>2.2</td></tr>");
});
/*$(".child").click(function(){
	alert($(this).text());
});*/
$("#tbody1").on("click",".child",function(){
	alert($(this).text());
});
</script>
</body>
</html>
代码解释:

对于所有在id值为"tbody1"下的元素且具有class是''child'的元素进行事件绑定。所以即使是新添加的元素也可以有事件效果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值