简体   繁体   中英

Getting value from this JQuery plugin

I've been experimenting with writing JQuery plugins lately, and I'm sure this is a very simple question. But, I seem to not be able to get a value inside of my plugin.

For example, I have the following code:

plugin.js

$(function($) {
  $.fn.myPlugin = function() {
    // alert the id from main.js
  }
});

main.js

$(document).ready(function() {
  $('#someDIV').attr('id').myPlugin();
});

You cannot define plugin on string . Use selector to call the plugin.

Have a look at this .

Use it like this:

(function ($) {
    $.fn.myPlugin = function () {
        this.each(function () {
            // Allow multiple element selectors
            alert(this.attr('id'));
        });

        return this; // Allow Chaining
    }
} (jQuery));

$('.myClass').myPlugin();

DEMO

Tutorial

Try this:

(function($) {
    $.fn.myPlugin = function() {
        alert($(this).attr('id'));
    }
}(jQuery));

See here: http://jsfiddle.net/1cgub37y/1/

You should pass only the object into your jQuery-extension function (not the object's ID), as below or in this fiddle (will alert "someDIV" onload):

// jQuery extension
// The object passed into jQuery extension will occupy keyword "this"
$(function($) {
  $.fn.myPlugin = function() {
      // Get the ID (or some other attr) of the object.
      var id = $(this).attr("id");

      // Now do something with it :)
      alert(id);
  }
});

$(document).ready(function() {
  $('#someDIV').myPlugin();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM