Jquery - (重新)连接动态生成的元素 [英] Jquery - (re)wiring dynamically generated elements

查看:63
本文介绍了Jquery - (重新)连接动态生成的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我常常将元素挂钩添加功能,例如:

Often times I have elements hooked to added functionality, like:

$('.myfav').autocomplete();
$('.myfav').datepicker();
$('.myfav').click(somefunction);

但是当通过某些代码动态生成此类的更多实例时,新的 $('。myfav')已经死了,需要重新布线,所以我这样做:

But when more instances of this class are generated dynamically through some code, the new $('.myfav') are dead and need rewiring, so I do this:

$("#somelink").click(function(){
     //generate 10 new $('.myfav') and append them to the DOM
     //re-wire them again as in the block above
     $('.myfav').autocomplete();
     $('.myfav').datepicker();
     $('.myfav').click(somefunction);
});

这意味着我最终拥有2个相同的代码块,1个用于初始页面加载和一个重新连接动态生成的新元素。这不是DRY代码,效率不高。

What this means is that I end up having 2 identical blocks of code, 1 for the initial page load and one to rewire the new elements that get generated dynamically. This isn't DRY code and isn't very efficient.

这真的是完成这项工作的唯一方法,还是有其他最佳做法?我的直觉告诉我,有一些比这更有效的东西(也是为了帮助干掉代码)。

Is this really the only way to get this done, or there another best practice? My gut tells me there's gotta be something more efficient than this (also to help DRY the code).

更新

看起来.live与.click的效果很好,正如cletus所解释的那样。

Looks like .live works well with .click as explained by cletus.

$('.myfav').live("click", somefunction);

但我尝试使用自定义设置的插件,例如.autocomplete,但它无效。
我试过这个:

But I tried it with custom-set plugins like .autocomplete and it didn't work. I tried this:

$('.myfav').live("click", autocomplete("somefile.php", {max: 15, mustMatch: true}));

所以直播看起来不能处理这些自定义插件(当然我可能错了,如果你知道的话请更新)

So live doesn't look like it can handle these custom plugins (of course I could be wrong, please update if you know something)

推荐答案

.live()文档说...

The .live() documentation says ...


.live不支持liveQuery提供的无事件样式回调。只有事件处理程序可以与.live绑定。

.live doesn't support the no-event style callback that liveQuery provides. Only event handlers can be bound with .live.

所以我看了一下 liveQuery ,我认为它将完全满足您的需求,具体如下:

So I took a look at liveQuery, and I think it will do exactly what you need with something like the following:

$('.myfav').livequery(function() {
  $(this).autocomplete();
  $(this).datepicker();
  $(this).click(somefunction);
});

看似方便!

这篇关于Jquery - (重新)连接动态生成的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆