Can I have two jquery onclick events in one element?

回眸只為那壹抹淺笑 提交于 2019-12-18 04:37:12

问题


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>


来源:https://stackoverflow.com/questions/17202986/can-i-have-two-jquery-onclick-events-in-one-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!