最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - 2 different on click events conflict? - Stack Overflow

programmeradmin3浏览0评论

I have one link:

<a href="javascript:void(0)" class="lorem hello"> link </a>

And I have two different onclick function set to the two classes like this:

jQuery(".lorem").each(function(){
    this.onclick = function() {

        // stuff

    }
});

and

jQuery(".hello").each(function(){
    this.onclick = function() {

        // stuff

    }
});

This stops the top one to work. Why? And how can I make both functions work while being separated?

I have one link:

<a href="javascript:void(0)" class="lorem hello"> link </a>

And I have two different onclick function set to the two classes like this:

jQuery(".lorem").each(function(){
    this.onclick = function() {

        // stuff

    }
});

and

jQuery(".hello").each(function(){
    this.onclick = function() {

        // stuff

    }
});

This stops the top one to work. Why? And how can I make both functions work while being separated?

Share Improve this question asked May 22, 2015 at 15:44 Henrik PettersonHenrik Petterson 7,12421 gold badges81 silver badges159 bronze badges 1
  • 3 jQuery and onclick handlers? You are doing something anti-pattern. Use the jQuery on method for binding event handlers. – Ram Commented May 22, 2015 at 15:46
Add a ment  | 

2 Answers 2

Reset to default 6

You can only assign one function to the onclick property. You should use normal jQuery event binding, it allows multiple handlers:

$(".lorem").click(function() {
    // stuff
});
$(".hello").click(function() {
    // stuff
});

If you want to do it with native Javascript, you can use addEventListener; as the name suggests, these are additive, they don't replace.

jQuery(".lorem").each(function(){
    this.addEventListener("click", function() {

        // stuff

    })
});
jQuery(".hello").each(function(){
    this.addEventListener("click", function() {

        // stuff

    })
});

When you are using query, why use .onclick on the DOM element (therefore overwriting the previous binding). Instead use jQuery's .on:

$('.lorem').on('click', function(){
  // something
});
$('.hello').on('click', function(){
  // something else
});
发布评论

评论列表(0)

  1. 暂无评论