脚本只被调用一次:
$(document).on('click', '.class', function() { //code here });
但它工作得很好,使用:
$('.class').on('click', function() { //code here });
and
$('.class').click(function() { //code here });
我需要以 $(document) 为目标,因为我要附加可以稍后控制的动态元素。
这是我现在拥有的确切代码:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script>
$(document).ready(function() {
$(document).on('click', ".dropdown button", function() {
alert("hi");
});
});
</script>
</head>
<body>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</div>
</body>
</html>
无论如何,我可以多次触发脚本事件我正在使用 $(document) 或者有什么方法可以实现这一点?
最佳答案
看起来您正在使用的 Bootstrap 版本中存在某种错误。
我放下一个引用:
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
并且函数触发每个按钮点击,但是下拉列表看起来有点不同,可能应该附加一些其他类,或者您需要使用一些手动样式来恢复菜单样式。
关于javascript - 使用 $(document) 仅调用一次脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53202302/