所有id以自定义文本开头的按钮上的JQuery单击事件
JQuery click event on all buttons with id starting with custom text
使用JQuery,我需要编写一个函数,在单击两个按钮(edit0、edit1)时调用。我有以下代码:
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$('[id^=edit]').click(function() {
alert("1111");
});
</script>
</head>
<body>
<button id="edit0" class="edit"> edit </button>
<button id="edit1" class="edit"> edit </button>
</body>
</html>
当我运行它时,点击按钮不会发生任何事情。我试图用替换脚本
$('button[class="edit"]').click(function() {
alert('1111');
});
但结果是一样的。
您可以简单地使用CSS3[attribute ^=value]Selector来实现"在id以自定义文本开头的所有按钮上单击事件",如下所示。
$('button[id^="edit"]').click(function() {
alert('111');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<button id="edit0" class="edit"> edit </button>
<button id="edit1" class="edit"> edit </button>
<script type="text/javascript">
$('[id^=edit]').click(function() {
alert("1111");
});
</script>
</body>
</html>
此外,将代码放在闭包</body>
标记之前,以确保代码运行时您的dom已准备就绪。
我通常看到用于寻址自定义属性的语法,请尝试一下。
$('button.edit').click(function() {
alert('1111');
});
还要将脚本放在HTML下方。或者在文档上使用jQuery。请记住,JavaScript/JQuery是按顺序执行的。
相关文章:
- 如何隐藏按钮单击事件上的占位符
- 从Web服务器下载图像按钮单击使用JavaScript
- 在SweetAlert中传递ASP.NET按钮单击事件
- 单选按钮单击可刷新/更改网站的小区域
- 调用按钮单击事件 ajax 加载的用户控件
- 附加 jQuery 代码以在加载和按钮单击时运行
- 在按钮单击时将图像URL数据显示到弹出框中,而无需禁用背景
- 按钮单击服务器单击
- 触发单选按钮单击,并在页面刷新时记住选择
- 如何使用 javascript 而不是使用控制器中的方法在 rails 中呈现部分按钮单击
- jQuery UI 选项卡 - 将参数设置为下一个/上一个按钮单击
- 如何在 Angular JS 中的按钮单击上添加类
- 当元素上有多个类时触发按钮单击事件
- 如何在 HTML 中的按钮单击上更改图像(IMG URL 每次来自服务器)
- 如何使用javascript刷新我的html页面时清除按钮单击
- 阻止后退按钮 - 单击按钮时忽略
- 如何制作按钮.单击“开始时不运行”
- Rails:尝试在按钮单击时渲染部分
- 在页面加载时调用函数,在按钮单击时再次调用函数,但参数不同
- 如何在服务器端的文本中添加按钮单击事件