分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

jQuery动态添加的节点事件无法触发

发布时间:2023-09-06 01:07责任编辑:沈小雨关键词:jQuery

添加节点之前如图:

点击图中的 "第一个" 之后会触发click事件,效果如图:

点击按钮的之后,添加节点之后如图:

这时点击图中的 "第一个",却不会触发click事件。

此时代码如下: 

<!DOCTYPE html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><html><head><script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script><script> ???$(function(){ ???????$(".a1").on("click",function(){ ???????????alert("触发a标签的点击事件!"); ???????}); ???????}); ???????function cl(){ ???????$(".div2").html(‘<a class="a1">第一个</a><br><a class="a2">第二个</a>‘); ???}</script></head><body> ???<div class="div1"> ???????<div class="div2"> ???????????<a class="a1">第一个</a> ???????????????????</div> ???????<input onclick="cl()" type="button" value="添加节点"/> ???</div></body></html>

以上问题可以通过绑定几种方法解决

1.是直接在添加标签的时候添加一个onclick事件;

2.通过绑定这个标签的父类或者body来达到激活click事件的效果。

改过之后的代码如下:

<!DOCTYPE html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><html><head><script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script><script> ???$(function(){ ???????/*$(".a1").on("click",function(){ ???????????alert("触发a标签的点击事件!"); ???????});*/ ???????????????????/*$(".div1").on("click",".a1",function(){ ???????????alert("触发a标签的点击事件!"); ???????});*/ ???????????????$(".div2").on("click",".a1",function(){ ???????????alert("触发a标签的点击事件!"); ???????}); ???????????????/*$("body").on("click",".a1",function(){ ???????????alert("触发a标签的点击事件!"); ???????});*/ ???}); ???????function cl(){ ???????$(".div2").html(‘<a class="a1">第一个</a><br><a class="a2">第二个</a>‘); ???}</script></head><body> ???<div class="div1"> ???????<div class="div2"> ???????????<a class="a1">第一个</a> ???????????????????</div> ???????<input onclick="cl()" type="button" value="添加节点"/> ???</div></body></html>

如果出现,点击一次,出现两次click事件的话,

考虑使用propagation()方法处理冒泡。

jQuery动态添加的节点事件无法触发

原文地址:http://www.cnblogs.com/GoneLW/p/7450768.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved