链接到boostrap的Javascript代码会阻止onclick事件处理程序运行

Linking to boostrap's Javascript code prevents onclick event handler from running?

本文关键字:onclick 事件处理 程序 运行 boostrap Javascript 代码 链接      更新时间:2023-09-26

这个简单的测试页面旨在显示一个链接,并在用户单击它时弹出警报。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
        
        <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
    
    <!-- uncommenting the next line prevents the alert from showing up -->
    <!-- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js">  -->
        <script type="text/javascript">
          
        $( document ).ready(function() {
        $("#show_more_link").click(function(e) {
            alert("on click running");
            e.preventDefault();
        });
    });
    </script>   
</head>
<body>
    <a id="show_more_link" href="#">click here</a>
</body>
</html>

问题:取消注释包含 Bootstrap 缩小的 Javascript 的行(第 #10 行(会破坏 onclick 事件:

  • 如果该行被注释掉,单击链接会弹出警报(按预期(。

  • 如果该行未注释,则单击该链接不执行任何操作。

为什么会这样?

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js">  

您的脚本未关闭/缺少结束</script>标记,这就是您收到错误并且代码中断的原因,您需要这样做:

 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>