0

I am creating a jQuery plugin that calls the on method. Now I need to get the selector string from inside that method. Is there a way I can do that?

(function($) {

        return this.each(function () {
            var $this = $(this);

            $(document).on('click', 'a[href="#post"]', function(event) {
                event.preventDefault();

                // I need to get the 'a[href="#post"]' string from here
        });
    });
}
})(jQuery);

Thanks you.

Rendicahya
  • 4,205
  • 7
  • 36
  • 56

3 Answers3

1

See my post here if you need to display your "a" tag as string

$('<div>').append($this.clone()).html();

jsFiddle available here

http://jsfiddle.net/F3Vrk/

Community
  • 1
  • 1
Mordhak
  • 2,646
  • 2
  • 20
  • 14
1

really not sure what you are after but you have full access to the element within the on() method using this

(function($) {

    return this.each(function () {
        var $this = $(this);

        $(document).on('click', 'a[href="#post"]', function(event) {
            event.preventDefault();

            alert( $(this).attr('href') );
       });
    });
  };
})(jQuery);

As for the actual selector string... it is hard coded into your example so not really sure what you are asking with regard to that part

charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

jQuery does not supply this information, but there are other approaches that come to mind. For example:

(function() {
    var selector = 'a[href="#post"]';
    $(document).on('click', selector, function(event) {
        event.preventDefault();
        console.log(selector);
    });
})();

See it in action.

However this is a somewhat questionable practice and it's likely that there are other, simpler, ways to achieve your aim.

Jon
  • 428,835
  • 81
  • 738
  • 806