在 AJAX 加载的内容上运行 JQuery 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4226316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:52:40  来源:igfitidea点击:

Running JQuery scripts on AJAX loaded content

jqueryajax

提问by mmcglynn

I am using .load() to pull static HTML files onto my main HTML page. The scripts and selectors that I have written exist within:

我正在使用 .load() 将静态 HTML 文件拉到我的主 HTML 页面上。我编写的脚本和选择器存在于:

$(document).ready(function(){});

But they don't work on the AJAX loaded content. I have read that this is because the selectors that I am using are not available.

但它们不适用于 AJAX 加载的内容。我读到这是因为我使用的选择器不可用。

Is there a better way to do this? Adding the script to the window.load function doesn't work either:

有一个更好的方法吗?将脚本添加到 window.load 函数也不起作用:

$(window).load(function() {});

回答by Jman

$(document).ajaxComplete(function(){
    // fire when any Ajax requests complete
})

ajaxComplete()

ajaxComplete()

回答by Adam Kiss

There are more than one option:

有不止一种选择:

  1. you can add initialization scripts [ $(this).click...] into callbackfunction of $.load()
  2. you can use $.live(), which creates handlers even for dynamically loaded/created objects.
  1. 您可以添加初始化脚本[ $(this).click...]进入callback功能$.load()
  2. 您可以使用$.live(),它甚至为动态加载/创建的对象创建处理程序。

More here:
callback: http://api.jquery.com/load/(notice the "complete()" function)
bind: http://api.jquery.com/live/

更多信息
回调:http: //api.jquery.com/load/(注意“ complete()”函数)
绑定:http: //api.jquery.com/live/

Edit: My mistake, it was live(), not bind(), thank you guys

编辑:我的错误,是live(),不是bind(),谢谢你们

回答by Stephen Watkins

You can bind events to dynamically loaded content via jQuery's $.live().

您可以通过 jQuery 的$.live().

From jQuery http://api.jquery.com/live/:

来自 jQuery http://api.jquery.com/live/

Attach a handler to the event for all elements which match the current selector, now and in the future.

将处理程序附加到与当前选择器匹配的所有元素的事件,现在和将来。

回答by Scott Evernden

jQuery loadtakes an optional callback function argument which you could use to do any setup you need AFTER your ajax-ed content is loaded

jQuery 加载采用可选的回调函数参数,您可以使用该参数在加载 ajax 内容后进行任何所需的设置