简体   繁体   English

在jQuery中,如何在指定元素之后加载ajax内容

[英]In jQuery, how to load ajax content after a specified element

I have the following HTML: 我有以下HTML:

<div id="mydiv">
</div>

I would like to load content using jQuery so it appears after my DIV. 我想使用jQuery加载内容,所以它出现在我的DIV之后。

I've tried this: 我试过这个:

$("#mydiv").load("/path/to/content.html");

However, this ends up with this result: 但是,这最终得出以下结果:

<div id="mydiv">
<p>content from file</p>
</div>

How do I get this result? 我如何得到这个结果?

<div id="mydiv">
</div>
<p>content from file<p>

Anyone still looking for solution, I would suggest using jQuery.get() instead of .load() to load AJAX content. 任何人仍在寻找解决方案,我建议使用jQuery.get()而不是jQuery.get() .load()来加载AJAX内容。 Then use .after() function to specify the preceding element. 然后使用.after()函数指定前面的元素。

Here's an example: 这是一个例子:

$.get('url.html', function(data){ // Loads content into the 'data' variable.
    $('#mydiv').after(data); // Injects 'data' after the #mydiv element.
  });

使用after函数。

I have one interesting but rather hard and difficult for understanding method, but using .load function. 我有一个有趣但相当困难和难以理解的方法,但使用.load函数。 So, code: 所以,代码:

$('#div_after').remove();
$('#mydiv').after($('<div>').load('/path/to/content.html #div_after', {
    data: data, //variables to send. Useless in your case
}, function () {
    $(this).children().unwrap();}
));

See, I put .remove() method to remove previously created div if you use this code more than once. 如果您多次使用此代码,请参阅,我将.remove()方法删除以前创建的div。 You can delete first line if it will be used just once. 如果只使用一次,您可以删除第一行。 The idea is .after($'') creates noname div element on the page after #mydiv and .load() the html into it with callback-function 想法是.after($'')在#mydiv和.load()之后在页面上创建noname div元素html进入回调函数

$(this).children().unwrap();

which is logically will unwrap into our noname div and "rename" it to our #div_after from loading html. 这在逻辑上将打开我们的noname div并从加载html“重命名”到我们的#div_after。 It is also unnecessary if you wish using just noname div. 如果你只想使用noname div,也没有必要。

Cheers! 干杯!

PS It took me a while in a project to combine all this stuff together :) I wish it would be useful. PS我花了一段时间在一个项目中将所有这些东西组合在一起:)我希望它会有用。

使用after(内容)功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM