2011-05-17 98 views
0

我很努力讓自己的頭腦在我自定義jQuery插件中創作(並附加到事件)的方式。jQuery事件綁定

我有一個插件的開始,在這個簡單的例子....

http://jsfiddle.net/ETFairfax/mRAHF/9/

(function($) { 
    $.fn.myPlugIn = function(options) { 
     var defaults = { 
      'width': 200, 
      'url': 'www.someurl.com' 
     }; 
     // If options exist, lets merge them with our default settings 
     var options = $.extend({}, defaults, options); 

     function somePrivateFunction() { 
      return options.url; 
     } 

     return this.each(function() { 
      $(this).text(somePrivateFunction()); 
      $(this).width(options.width); 
     }); 
    }; 
})(jQuery); 

$(document).ready(function() { 

    $('#testDiv1').myPlugIn({ 
     'width': 150 
    }); 
    $('#testDiv2').myPlugIn({ 
     'url': 'www.google.com' 
    }); 
}); 

<div id="eventDriver1">Click here to update 1</div> 
<div id="eventDriver2">Click here to update 2</div> 
<div id="testDiv1" class="testClass"></div> 
<div id="testDiv2" class="testClass"></div> 

正如你可以看到我設置testDiv1和testDiv2,和他們的行爲如我所料。

現在我想能夠說eventDriver1應該刷新testDiv1,併爲它指定什麼文本shoudl進入它。我只是不知道從哪裏開始!

我很欣賞那將在某個地方被記錄,和/或已經問過,但我只是不知道什麼流行語我需要搜索!任何幫助讚賞。

謝謝。

+1

綁定事件與'.bind完成()'或'.live()'或使用的一個快捷鍵(例如'.click()','.submit()','.load()'等)。我不確定你的問題是什麼... – Chad 2011-05-17 19:01:02

+0

請在問題中包含你的代碼。謝謝。 – user113716 2011-05-17 19:03:09

回答

1

如何:

Live Demo

$('#eventDriver1').click(function() { 
    $('#testDiv1').myPlugIn({'url': 'www.yahoo.com'}); 
}); 
$('#eventDriver2').click(function() { 
    $('#testDiv2').myPlugIn({'url': 'www.microsoft.com', 'width': 250}); 
}); 
jQuery中
+0

感謝您的例子,雖然它工作得很好,我很高興使用該方法,如果它的方式來做到這一點,但我試圖找出如何公開某種Update()方法插件,以及如何調用它。也許我對錯綜複雜的事情有錯誤的想法? – ETFairfax 2011-05-17 20:04:22

1

使用點擊。

$('#eventDriver1').click(function(){/*do something*/}) 
+0

感謝您的回覆,但它是/ *做的東西* /位,我很困惑。我試圖找出如何在插件上公開某種Update()方法,以及如何調用它?那有意義嗎? – ETFairfax 2011-05-17 20:06:19