我想在jQuery選擇器上調用一個函數。如果在選擇器上調用一個jquery函數,如何在我調用的函數中檢索選擇器?
下面是我在做我的網頁上的內容:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>first</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../myplugin.js"></script>
</head>
<body>
<div class="foo"></div>
<script type="text/javascript">
// my custom function
$(".foo").addGadget({ "src":"gadgets/menu.html", "param":{"filter":"office"}},
function (error, response) {
console.log("hello!!!");
});
</script>
</body>
</html>
所以我希望能夠在$('foo')
調用我的自定義功能addGadget()
。這適用所有權利:
(function (window, jquery, undefined) {
var that = {};
that.addGadget = $.fn.addGadget = function (options, callback) {
console.log("I'd like to access my element here");
console.log(this);
console.log($(this));
};
return window.myPlugin = that;
}(window, $));
所以我可以打電話都
myPlugin.addGadget();
$('.foo').addGadget();
問題是,我無法訪問foo
我的方法內。
問:
什麼我需要改變,以能夠訪問foo
我的addGadget
方法裏面?
謝謝!
可能重複的[獲取最初的選擇器裏面的jquery插件](http://stackoverflow.com/questions/5477394/getting-initial-selector-inside-jquery-plugin) – 2013-05-20 15:01:07
你正在傳遞' $'作爲'jquery',然後在函數中使用'$'?另外,'console.log(this)'輸出的是什麼? – Dogbert
@Dogbert:感謝'$/jquery'。 'console.log'不斷輸出'document' - 這就是爲什麼我發佈......只是再次檢查,現在它的工作原理。不知道爲什麼它沒有在之前。 – frequent