簡體   English   中英

從此JQuery插件獲取價值

[英]Getting value from this JQuery plugin

我最近一直在嘗試編寫JQuery插件,並且我敢肯定這是一個非常簡單的問題。 但是,我似乎無法在插件內部獲取價值。

例如,我有以下代碼:

plugin.js

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

main.js

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

您不能在string上定義插件。 使用selector調用插件。

看看這個

像這樣使用它:

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

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

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

演示

講解

嘗試這個:

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

看到這里: http : //jsfiddle.net/1cgub37y/1/

您應該只將對象傳遞到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