简体   繁体   English

从此JQuery插件获取价值

[英]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. 我最近一直在尝试编写JQuery插件,并且我敢肯定这是一个非常简单的问题。 But, I seem to not be able to get a value inside of my plugin. 但是,我似乎无法在插件内部获取价值。

For example, I have the following code: 例如,我有以下代码:

plugin.js plugin.js

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

main.js main.js

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

You cannot define plugin on string . 您不能在string上定义插件。 Use selector to call the plugin. 使用selector调用插件。

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/ 看到这里: 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扩展函数中(而不是对象的ID),如下所示或在提要中(将警告“ someDIV”加载):

// 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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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