2012-05-02 217 views
0

我創建了一個jQuery插件,現在我想其綁定到DOM這是由PHP腳本創建的元素。jQuery插件 - 動態綁定到元素

使用下面的標記爲例:

<div class="showcase_window"> 

<div id='mywhatever'></div> 
<div id='mywhatever2'></div> 
<div id='mywhatever3'></div> 

</div> 

這工作:

$(document).ready(function(){ 

    $('#mywhatever').showcase(); 
    $('#mywhatever2').showcase(); 
    $('#mywhatever3').showcase(); 
}); 

但由於標記是由PHP腳本創建的,我試圖得到這樣的工作:

$(document).ready(function(){ 

    $('.showcase_window').children().on('showcase'); 

    }); 

但我有點困惑......我明白'on'用於附加事件,但我我不知道如何去了解它...

非常感謝!

P.S:這裏是插件:

$.fn.showcase = function() { 

    return this.each(function() { 

     var $this = $(this); 

     $this.find(".sc_itm_display").hover(function() { 
      $this.find(".sc_img_front").stop(true,true).fadeOut("slow"); 
      }, function() { 
     $this.find(".sc_img_front").stop(true,true).fadeIn("slow"); 
     }); 

    $this.find('.sc_color_select img').click(function() { 

    var color_path_1 = $(this).attr("src").replace("color","1"); 
    var color_path_2 = $(this).attr("src").replace("color","2"); 

    $this.find('.sc_itm_display .sc_img_back img').attr("src",color_path_1); 
    $this.find('.sc_itm_display .sc_img_front img').attr("src",color_path_2); 

    }); 
    }); 
    }; 
+0

'on'僅適用於事件。不用於附加插件的東西。 – gdoron

+0

不知道,但嘗試這個... $( 'showcase_window。')兒童()上。({ 點擊:函數(){ this.showcase();} }); – sree

回答

1

on重視處理事件。事件可以是用戶操作或進程完成/失敗等。

你沒有附加一個事件,而是一個函數,在這種情況下,jQuery爲你做。

$('.showcase_window').children()或者乾脆$('.showcase_window>div')包含腳本創建的三個例子的div。

$('.showcase_window').children().showcase();(或更有效地$('.showcase_window>div').showcase();

將爲每個這些div的執行showcase()一次。內showcasethis將是DIV( 'mywhatever')本身。

+0

明白了,非常感謝! – DimC

1

如果你的PHP是產生要採取行動的元素,用它來輸出與逗號的字符串的腳本分隔ID值的目標。然後將這些目標用於您的插件。

PHP輸出這樣的:

var target_ids = "#this, #that, #the_other"; 
在你的jQuery

$(target_ids).showcase(); 

或者,採用獨特的類來標記所有您要定位的元素,你不需要知道其ID。

$(".mywhatevers").showcase(); 
相關問題