简体   繁体   中英

How to use click event for anchor tag and button tag simultaneoulsy in jQuery?

I'm using jQuery 1.9.1 in my project. I've following HTML :

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

I want to display the same alert message if user clicks on a icon enclosed in anchor tag with class "btn_delete" or click on a button having id "btn_add".

For this I tried following code but it didn't work out for me.

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

Can someone please help me in this regard please?

If you want any more information regarding the issue I'm facing please let me know.

Thanks in advance.

   **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!")
   });
<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>

Your code is quite close to what it should be. Change:

$("button#btn_add.btn_delete")

To:

$("#btn_add,a.btn_delete")

You can use , to have multiple selectors.

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

You can have both the HTML Tag in the jQuery selector as below:

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

Hope this helps!

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

Additionally to the other answers:

Your current selector will find elements like this:

<button id="btn_add" class="btn_delete">Foo</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM