jquery load() 并追加

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

jquery load() and append

jquery

提问by Daniele

silly quick question:

愚蠢的快速问题:

I have my:

我有我的:

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

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.

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

采纳答案by Aleja_Vigo

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

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”,以便您等待响应。如果您不等待它(正常的 Ajax 异步调用),您将有一个未知时间的未定义变量,因此它可能很危险。

EDIT: 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.

编辑:正如评论正确地说的那样,使用“async:false”并不常见并且很难看。通常,您会操作响应并将其插入到成功回调内的 DOM 中。仅当您确实需要变量中的响应等待另一件事使用该变量时才需要使用异步,这不是常见的事情发生。

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

回答by Sven Bieder

You mean something like this?

你的意思是这样的?

var content;
$.get('ajax/test.html', function(data){
    content= data;
    $('#result').prepend(content);
});

That saves your loaded content into a variable first and you can manipulate it however you want.

这首先将您加载的内容保存到一个变量中,您可以随意操作它。

回答by Ry-

A quick way might be:

一个快速的方法可能是:

$('#result').append($('<div>').load('ajax/test.html'));

回答by Shyju

Do a jQuery post and load the data to a vaiable and prepend to the desired div

做一个 jQuery 帖子并将数据加载到一个变量并添加到所需的 div

$.post('ajax/test.html', function(data) {
  $('#result').prepend(data);  
});

回答by Márcio SULZBACH

I think this is a shorter soluction

我认为这是一个较短的解决方案

$.get("ajax/test.html",function (dados) { $("#result").append(dados);});