Adding jQuery live search to dynamic inputs

自古美人都是妖i 提交于 2020-01-17 03:34:46

问题


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.

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.

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).

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

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

Thanks much.


回答1:


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

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() requires jQuery 1.7+

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

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

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



来源:https://stackoverflow.com/questions/13887697/adding-jquery-live-search-to-dynamic-inputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!