0

I have written a jQuery plugin which has similar functionality as following:

  <h1 id="t1">title 1</h1>
  <h1 id="t2">title 2</h2>
<script>
$.fn.extend({
  test: function(opts){
    var o = { text : 'hello '};
    o = $.extend( o, opts  );
    return this.each(function(){
      var $this = $(this);
      $div = $('<div/>');
      $btn  = $('<button />').text(o.text);
      $btn.click(function(){
        $div.text(o.text);
      });
      $this.after($btn).after($div);
    });
  }
});

$('#t1').test({text:'hola '});
$('#t2').test({text:'nihao '});
</script>

in which I have created some elements (a button and a div) on the fly and added some event bindings. In the sample code I have more than one element that will use this plugin respectively. However I noticed when I trigger the event, my bound event also applies changes to the last div I have created in the plugin.

Where have I done wrong?

0

1 Answer 1

1

You missed the var in front of your $div and $btn and created global variables by accident.

Sign up to request clarification or add additional context in comments.

1 Comment

Cant believe I missed this... thanks alot! The code worked as intended after adding var!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.