所有id以自定义文本开头的按钮上的JQuery单击事件

JQuery click event on all buttons with id starting with custom text

本文关键字:按钮 单击 事件 JQuery 开头 id 自定义 文本 所有      更新时间:2023-09-26

使用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是按顺序执行的。