我可以在一个元素中有两个 jquery onclick 事件吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17202986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I have two jquery onclick events in one element?
提问by Sushanth --
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.
有人可以帮我将第二个功能添加到第一个 onclick 事件中。
回答by Sushanth --
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.
注意:使用 javascript 绑定事件总是一个更好的主意,因为它保持关注点分离和可维护性目的。
You can bind multiple events to the elements in your JS code instead which is lot cleaner
你可以将多个事件绑定到你的 JS 代码中的元素,这样更简洁
jQuery
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
原生 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
});
回答by faffaffaff
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.
尝试替换“return false;” 用“event.preventDefault();”。这应该让事件向上传播,以便点击处理程序触发,但仍会阻止 a-href 导航。
回答by hamstu
It's generally considered bad practice to use the onclick
attribute. It mingles too much of the structure (HTML) with the behaviour (JavaScript).
使用该onclick
属性通常被认为是不好的做法。它将太多的结构 (HTML) 与行为 (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>