2012-05-02 158 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(); 
相关问题