我可以在一个元素中有两个 jquery onclick 事件吗? [英] Can I have two jquery onclick events in one element?

查看:16
本文介绍了我可以在一个元素中有两个 jquery onclick 事件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道以前有人问过这个问题,但我什至无法完全理解如何在一次单击中添加我的特定功能.

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.

当前点击代码:

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

要添加的第二个事件:

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

请有人帮我将第二个函数添加到第一个 onclick 事件中.

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

推荐答案

您可以将多个事件(相似)绑定到同一个元素.但是,如果您使用内联事件处理程序绑定事件,则最多可以定义一个事件.

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.

注意: 使用 javascript 绑定事件总是一个更好的主意,因为它保持关注点分离并出于可维护性目的.

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

您可以将多个事件绑定到您的 JS 代码中的元素,这样更简洁

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
});

原版 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
});

检查小提琴

这篇关于我可以在一个元素中有两个 jquery onclick 事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆