Good day.

I try to write a plugin on for jquery, which would find specially marked divs and insert html-code into them. Freshly created elements must respond to the click event:

$('button[data-type="site"]').bind("click", function (e) {console.log(e,$(this));}); 

On the page there are 2 elements that are processed by the plugin:

 $('div[data-type="placeholder"]').myPlugin(); 

The strangeness (for me) is that when I click on the first button, I get 2 console.log outputs in the console, and when I click on the second button, I get one (which is the right behavior).

Why is the call to the event handler function called?

Example here http://test.controlcash.ru/b.php

    1 answer 1

    Nothing strange, you select a button with a selector, and the following happens.

    • create button
    • hang the event on the button // тут кнопка одна на нее вешаем обработчик
    • create button
    • hang the event on the button // а тут кнопки две, вешаем еще раз на первую и на новую

    to win you need to turn what you do in res3 into a jQuery object and hang a handler on it:

     $button = $(res_3).appendTo(this.$element); /...../ $button.on('click',function(){ /......./ }); 

    Do not forget to declare $button where the thread is higher.

    • one
      By the way, replace you can call string.replace (). replace (). replace (); and do not forget to write var! - zb '
    • Super! Thank! Then the selector to the button is not needed. - Boris
    • 2eicto: yes, in the end, I just replace and rewrote. - Boris