将jQuery实时搜索添加到动态输入 [英] Adding jQuery live search to dynamic inputs

查看:96
本文介绍了将jQuery实时搜索添加到动态输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery实时搜索插件,需要将其绑定到类的所有实例.我的课程实例可能是动态的,也可能不是动态的.

I am using the jQuery live search plugin and need to bind it to all instances of a class. My class instances may or may not be dynamic.

我知道我可以通过将其嵌套在jQuery Live函数E.G $(".myLink").live(click function(){});

I know I can accomplish binding it to the dynamic class instances by nesting it within a jQuery Live function, E.G $(".myLink").live(click function(){});

但是,我还需要非动态类也具有绑定.

However, I also need the non dynamic classes to have the binding as well.

如何在不两次定义liveSearch绑定的情况下完成此任务? (一旦文档准备好了静态元素,就在我的点击处理程序中为动态元素准备了一次.)

How can I accomplish this without defining my liveSearch binding twice? (Once at document ready for the static elements, and once in my click handler for the dynamic elements).

这是我的liveSearch代码,不确定是否重要.

Here's my liveSearch code, not sure if it matters.

$(".myClass").liveSearch({
url: 'foo.php',
id: 'liveSearchID',
parent: '.myParent',
});

非常感谢.

推荐答案

您可以使用jQuery .on()绑定liveSearch来呈现(非动态)或将来的元素,例如:

You could use jQuery .on() to bind liveSearch to present (non dynamic) or future elements like :

$("#parentContainer").on("click", ".myClass", function(){
  $(this).liveSearch({
     // options
  }); // liveSearch
}); // on

通知,您必须将.on()应用于选择器.myClass父容器,然后传递事件.myClass作为后代选择器,并且处理程序.

Notice that you have to apply .on() to the parent container of your selector .myClass and then pass the event, .myClass as descendant selector and the handler.

请参见 演示

See DEMO

.on()需要jQuery 1.7 +

.on() requires jQuery 1.7+

编辑(太平洋时间2012年12月15日-下午4:13):

EDIT (Dec 15, 2012 - 4:13pm PT):

较旧版本的jQuery的用户应优先使用.delegate()而不是.live() ...,所以只需像这样调整代码.delegate(selector, eventType, handler)(仍将.delegate()应用于父容器)即可:

Users of older versions of jQuery should use .delegate() in preference to .live() ... so just tweak your code this way .delegate(selector, eventType, handler) (still applying .delegate() to the parent container) like :

$("#parentContainer").delegate(".myClass", "click", function() {
  $(this).liveSearch({
     // options
  }); // liveSearch
}); // delegate

使用.delegate()查看新的 DEMO (需要jQuery v1.4.2 + )

See new DEMO using .delegate() (requires jQuery v1.4.2+)

这篇关于将jQuery实时搜索添加到动态输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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