1

我在我的项目中使用jQuery 1.9.1 。我有以下 HTML :

<button type="button" id="btn_add" class="btn btn-primary">Add</button>
<a class="btn_delete" href="#"><i class="icon-trash"></i></a>

如果用户单击包含在类“btn_delete”的锚标记中的图标或单击 ID 为“btn_add”的按钮,我想显示相同的警报消息。

为此,我尝试了以下代码,但对我没有用。

$(document).ready(function() {
  $("button#btn_add.btn_delete").on("click", function(event) { 
    event.preventDefault();
    alert("This action has been temporarily disabled!")
  });
});

有人可以在这方面帮助我吗?

如果您想了解有关我面临的问题的更多信息,请告诉我。

提前致谢。

4

7 回答 7

2
   **Approach #1**
   function doSomething(){
    //your code
   }

   $('#btn_add').click(doSomething);
   $('.btn_delete').click(doSomething);

   **Approach #2**
   $("#btn_add,a.btn_delete").on("click", function(event) { 
      event.preventDefault();
      alert("This action has been temporarily disabled!")
   });
于 2014-11-24T06:17:41.150 回答
2
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

 $(document).ready(function() {
 $("button#btn_add, a.btn_delete").on("click", function(event) { 
 event.preventDefault();
  alert("This action has been temporarily disabled!")
});
});

</script>
于 2014-11-24T06:24:38.430 回答
1

Additionally to the other answers:

Your current selector will find elements like this:

<button id="btn_add" class="btn_delete">Foo</button>
于 2014-11-24T06:19:26.327 回答
1

您的代码与应有的代码非常接近。改变:

$("button#btn_add.btn_delete")

至:

$("#btn_add,a.btn_delete")
于 2014-11-24T06:06:16.423 回答
1

您可以使用,多个选择器。

$(".btn_delete i,#btn_add").on("click", function(event) {
    event.preventDefault();
    alert("This action has been temporarily disabled!")
});
于 2014-11-24T06:06:37.097 回答
1

您可以在 jQuery 选择器中同时拥有 HTML 标记,如下所示:

$(document).ready(function() {
  $("button#btn_add, a.btn_delete").on("click", function(event) { 
    event.preventDefault();
    alert("This action has been temporarily disabled!")
  });
});

希望这可以帮助!

于 2014-11-24T06:09:06.090 回答
1
$(document).ready(function() {
    $("#btn_add,.btn_delete").on("click", function(event) { 
        event.preventDefault();
        alert("This action has been temporarily disabled!")
   });
});
于 2014-11-24T06:10:21.903 回答