[英]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();
});
嘗試這個:
(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.