您现在的位置是:技术博客 > 前端前端 动态DOM的事件绑定 Lucas2019-04-25 20:35【代码】1676人已围观 简介动态生成的DOM元素,使用常规的方式绑定事件无法触发。 工作中可能会发现动态添加的dom元素上的事件无法触发,如何解决? #### 一、场景代码如下 ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script typet="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script> </head> <body> <div class="one"> <span class="two" > <span>热爱:<input type="text" name="love"><span class="del" style="cursor:pointer;"> - </span></span> </span> <span class="three add" style="cursor:pointer"> + </span> </div> </body> </html> <script type="text/javascript"> $('.add').on('click',function(){ var that = $('.add'); var html = '<span class="two" ><span>热爱:<input type="text" name="love"><span class="del" style="cursor:pointer"> - </span></span></span>'; console.log(that); that.before(html); }); // 常规写法,无法触发 $('.del').click(function(){ var that = $(this); that.parent().remove(); }); </script> ``` #### 二、改后的js代码如下 1、方案一:元素层级绑定的方式 ``` <script type="text/javascript"> $('.add').on('click',function(){ var that = $('.add'); var html = '<span class="two" ><span>热爱:<input type="text" name="love"><span class="del" style="cursor:pointer"> - </span></span></span>'; console.log(that); that.before(html); }); // 元素层级绑定 $('.one').on('click','.del',function(){ var that = $(this); that.parent().remove(); }); </script> ``` 2、方案二:行内事件绑定 ``` <script type="text/javascript"> $('.add').on('click',function(){ var that = $('.add'); var html = '<span class="two" ><span>热爱:<input type="text" name="love"><span class="del" onclick="del_tr(this)" style="cursor:pointer"> - </span></span></span>'; console.log(that); that.before(html); }); // 行内绑定 function del_tr(obj){ var that = $(obj); that.parent().remove(); } </script> ``` > 提示:解决方式是,不直接绑定事件,而是代替为以父元素绑定子元素的方式 转载:感谢您对Lucas个人博客网站平台的认可,非常欢迎各位朋友分享到个人站长或者朋友圈,但转载请说明文章出处“来源Lucas个人博客”。 很赞哦! ( 0 ) 上一篇:推荐一个炫酷的背景插件 下一篇:ueditor的正确打开方式 相关文章 ueditor工具栏浮动bug 有趣的js插件 推荐一个炫酷的背景插件 ueditor的正确打开方式 点击排行 生活不止眼前的苟且,还有诗和远方 十年一觉电影梦 奥地利基茨比厄尔 禅修治愈身心 自律成就自我 零边际成本社会 Modern PHP 鸟哥的Linux私房菜 本栏推荐 要技术,更要有创意 定时任务 Curl无法发送https请求 Lnmp环境搭建 常用的SQL函数 Windows的cmd指令 ueditor工具栏浮动bug 有趣的js插件 标签云 git laravel swoole javascript vue ajax html css sql linux docker flask django nginx apache thinkphp markdown sublime wechat layui photoshop nodejs mysql windows composer java maven springboot mybatis IDE 猜你喜欢 Swoole 基础篇一(初识) PHP进程管理器 正则的快速上手 Sublime代码格式化 Lnmp环境搭建 高并发库存防控超量 Linux之top命令 常用的SQL函数 站点信息 建站时间:2018-05-01 在线人数:1人 文章统计:263篇 总浏览量:222572次 统计数据:百度统计 个人信息:扫描二维码查看