javascript 如何选择通过 jQuery load() 函数加载的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4450825/
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-10-25 11:31:14  来源:igfitidea点击:

How to select an element loaded through the jQuery load() function?

javascriptjqueryajaxasynchronous

提问by finferflu

I am currently having trouble with the following (here is some sample code first):

我目前遇到以下问题(首先是一些示例代码):

<div id="container"></div>

<script type="text/javascript">
    $('#container').load('content.html');

    $('.elementInContentHTML').fadeIn();
</script>

In short, I want to be able to access elements that have been dynamically added to a page without attaching them to event handlers.

简而言之,我希望能够访问已动态添加到页面的元素,而无需将它们附加到事件处理程序。

I know about the live()method, but I do notwant to bind my action to any event, i.e. I just want to run some actions with these new elements without clicking them, focusing, blurring, etc.

我知道的live()方法,但我希望我的绑定行动对任何事件,即我只是想不点击它们,注重运行这些新元素的一些行动,模糊等。

回答by SLaks

The loadfunction is asynchronous.
Your next line runs before the content is loaded.

load函数是异步的。
您的下一行在加载内容之前运行。

You need to put your code inside the loadfunction's callback, so that it will only run after the new content is loaded:

您需要将代码放在load函数的回调中,以便它仅在加载新内容后运行:

$('#container').load('content.html', function() {
    $('.elementInContentHTML').fadeIn();
});

回答by Simon

You could try using the callback for when load completes? See http://api.jquery.com/load/

您可以尝试在加载完成时使用回调吗?见http://api.jquery.com/load/

$('#result').load('ajax/test.html', function() {
  alert('Load was performed.');
});