jQuery load()和追加 [英] jquery load() and append

查看:88
本文介绍了jQuery load()和追加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

愚蠢的快速问题:

我有我的:

$('#result').load('ajax/test.html');

但是如果我不想将加载的内容插入#result,而是将其放在#result之前,并保留所有先例元素怎么办?是否可以创建一个变量,将其装入内容,然后将其附加或添加到我的#result中?我想象其他一些场景,使用我的全新变量,可以在将其插入DOM之前对其进行操作.

but what if I don't want to insert my loaded content into #result, but prepend it to #result, maintaining all precedent elements? Is it possible to create a variable, load it with content and then append or prepend it to my #result? I imagine some other scenarios where with my brand new variable I can manipulate it before inserting it into the DOM.

推荐答案

var response;
$.ajax({ type: "GET",   
     url: "ajax/test.html",   
     async: false,
     success : function(text)
     {
         response= text;
     }
});
$('#result').prepend('<div>'+response+'</div>');

您需要"async:false",以便等待响应.如果您不等待它(正常的Ajax异步调用),那么您将在未知时间内拥有一个未定义的变量,因此可能很危险.

You need "async: false" so you WAIT for the response. If you dont wait for it (normal Ajax asynchronous call) you will have an undefined variable for an unknown time, so it could be dangerous.

正如评论正确地指出的那样,使用"async:false"并不常见并且很丑陋.通常,您将操纵响应并将其插入成功回调内的DOM中.仅当您确实需要变量中的响应来等待另一件事来使用该变量(而不是常见的事情)时,才需要使用异步.

As the comments rightly say, using "async:false" is not usual and is ugly. Normally you would manipulate the response and insert it in the DOM inside the success callback. The use of the async only would be required if you really need the response in a variable waiting for another thing to use that variable, not a common thing to happen.

$.ajax({ type: "GET",   
     url: "ajax/test.html",   
     success : function(text)
     {
         $('#result').prepend('<div>'+text+'</div>');
     }
});

这篇关于jQuery load()和追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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