Can I have two jquery onclick events in one elemen

2019-01-25 07:03发布

问题:

I know this has been asked before but I can't quite get the syntax of how to add my particular functions in one onclick even.

Current onclick code:

<a class="thumbLinkCart" href="#" onclick="simpleCart.add('name=lemon','price=7.99','image=images/thumbs/yellowgold.jpg');return false;"></a>

Second event to be added:

<script>
    $(document).ready(function() { 
      $('#demo12').click(function() { 
   $.growlUI('Item added to cart'); 
}); 
}); 
</script>

Could someone help me add the second function to the first onclick event please.

回答1:

You can have multiple events (similar) bound to the same element. But if you bind the events using inline event handler, you can utmost have one event defined.

NOTE : Always a better idea to bind events using javascript, since it maintains separation of concerns and for maintainability purposes.

You can bind multiple events to the elements in your JS code instead which is lot cleaner

jQuery

 $('#demo12').on('click', function() { 
    alert('1st click event');
    //  Add items to the cart here
});

$('#demo12').on('click', function() { 
    alert('2nd click event');
    //  Do something else
});

Vanilla Javascript

document.querySelector('#demo12').addEventListener('click', function() { 
    alert('1st click event');
    //  Add items to the cart here
});

document.querySelector('#demo12').addEventListener('click', function() { 
    alert('2nd click event');
    //  Do something else
});

Check Fiddle



回答2:

Try to replace "return false;" with "event.preventDefault();". That should let the event propagate up so the click handler triggers, but still stop the a-href from navigating.



回答3:

It's generally considered bad practice to use the onclick attribute. It mingles too much of the structure (HTML) with the behaviour (JavaScript).

Why not do it all together?

<a class="thumbLinkCart" href="#">Link</a>

And

<script>
  $(document).ready(function() { 
    $('.thumbLinkCart').click(function() {
      simpleCart.add('name=lemon','price=7.99','image=images/thumbs/yellowgold.jpg'); 
      $.growlUI('Item added to cart'); 
    }); 
  }); 
</script>