Why does my jQuery click handler appear to run multiple times for some of its targets?

前端 未结 7 517
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-11 10:34

I apply:

$(\".newContentLink\").click(function() {
    $(\"#test\").append(\"1\");
});

On this:



        
相关标签:
7条回答
  • 2021-01-11 11:08

    As chaos says, you're probably calling click() each time you add one, and they're accumulating.

    If you're adding these items to the document dynamically, and need to make sure this function is added to every one you add, how about using live?

    $('#contents').on('click', '.newContentLink', function() {
        $("#test").append("1");
    });
    

    This will make sure the rule is dynamically applied once to any qualifying class in the document.

    0 讨论(0)
  • 2021-01-11 11:09

    Not a jQuery bug - Working Demo

    There must be a problem with something else in your code. Where is the element with id="test" in your markup?

    EDIT:

    Just read chaos' answer, which sounds like a plausible explanation.

    By the way, element ids must be unique within HTML markup - this is part of the HTML specification and may be another possible explanation

    0 讨论(0)
  • 2021-01-11 11:12

    To make sure the function only execute once on one click event you may use $(".newContentLink").one();

    $(".newContentLink").one(function() {
        $("#test").append("1");
    });
    
    0 讨论(0)
  • 2021-01-11 11:17

    Try giving different names to your submit input elements.

    0 讨论(0)
  • 2021-01-11 11:22

    Unable to replicate. I suspect that you're misrepresenting — oversimplifying, mostly — your situation. To be precise, I believe you're dynamically adding those inputs, and calling $(".newContentLink").click(...) each time — which, naturally, keeps applying additional copies of the click handler to each .newContentLink in the page.

    So the most recent input you've created has one copy of the click handler and appends one 1. The second most recent has two copies and appends 11. The third has three and appends 111, etc.

    To prevent this, apply the click handler to your newly created DOM element, not $(".newContentLink") (which always means every .newContentLink).

    0 讨论(0)
  • 2021-01-11 11:22

    or you can unbind the click event each time you add a new element

    $('.newContentLink').unbind('click');
    
    $(".newContentLink").click(function() {
        $("#test").append("1");
    });
    
    0 讨论(0)
提交回复
热议问题