jQuery中对未来的元素绑定事件用 on

最近项目需要点击弹窗里面的a标签出现外连接跳转提示

<a href="javascript:void(0);"  target="_blank" id="swba" >弹窗提示</a>

开始代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no" />
        <title></title>
        <script src="images/jquery-1.11.1.min.js" type="text/javascript"></script>
        <script type="text/javascript" src="images/layer.min.js"></script>
        
    </head>
    <body>
        <a href="javascript:void(0);"  target="_blank" id="swba" ><em class="one-line special-t special-te">弹窗按钮</em></a>
        
        <script>
               $(function(){
                
                    $("#swba").click(function(){
                            layer.open({
                                type: 1,
                                title : '公告',
                                closeBtn: 1,
                                area: ['346px', 'auto'],
                                shadeClose: false,
                                content: '<div style="padding:10px; line-height:200%;"><div style="text-align:left;">请前往<a href="http://www.baidu.com/"  style="color:#174ed0;" onclick="return confirm('您访问的链接即将离开“***”网站,是否继续?');">http://www.baidu.com</a>搜索查询</div></div>'
                        });
                    })
               });
        </script>
    </body>
</html>

发现点击a标签后无提示窗选择直接跳转走了,打log事件也没有触发,检查代码也无问题,思来想去发现竟然是未来元素在作怪。

改后代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no" />
        <title></title>
        <script src="images/jquery-1.11.1.min.js" type="text/javascript"></script>
        <script type="text/javascript" src="images/layer.min.js"></script>
        
    </head>
    <body>
        <a href="javascript:void(0);"  target="_blank" id="swba" ><em class="one-line special-t special-te">弹窗按钮</em></a>
        
        <script>
               $(function(){
                
                    $("#swba").click(function(){
                            layer.open({
                                type: 1,
                                title : '公告',
                                closeBtn: 1,
                                area: ['346px', 'auto'],
                                shadeClose: false,
                                content: '<div style="padding:10px; line-height:200%;"><div style="text-align:left;">请前往<a href="http://www.baidu.com/"  style="color:#174ed0;" class="urlTip">http://www.baidu.com</a>搜索查询</div></div>'
                        });
                    })
                    
                    
                    $(document).on("click",".urlTip",function(){
                        return confirm('您访问的链接即将离开***网站,是否继续?');
                    })
               });
        </script>
    </body>
</html>

 

完美解决这个问题!

原文地址:https://www.cnblogs.com/webdom/p/10535221.html