使用 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 已准备好。
关于javascript - id 以自定义文本开头的所有按钮上的 JQuery 单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34616155/