JQuery ID 以自定义文本开头的所有按钮上的点击事件
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 来实现 'click event on all buttons with id starting with custom text',如下所示。
$('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 是顺序执行的。
使用 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 来实现 'click event on all buttons with id starting with custom text',如下所示。
$('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 是顺序执行的。