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

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

I apply:

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

On this:



        
7条回答
  •  失恋的感觉
    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).

提交回复
热议问题