2016-01-05 27 views
0

使用JQuery,我需要编写一个函数,点击任意一个按钮(edit0,edit1)。 我有以下代码:JQuery在所有按钮上点击事件,ID以自定义文本开头

<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'); 
}); 

但结果是一样的。

回答

3

您可以简单地使用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准备好了代码运行时。

0

我通常会看到解决自定义属性的语法,试试这个。

$('button.edit').click(function() { 
    alert('1111'); 
}); 

还把你的脚本放在你的HTML下面。或者在准备好的文档上使用jQuery。记得JavaScript/JQuery是按顺序执行的。

相关问题