这是我的代码
$('#right').load('textes.html #nicolas');
$('#right').load('textes.html #antoine');
问题是div antoine的内容在div中覆盖内容加载div nicolas
div #right:从文件textes.html = ok加载div nicolas div #right:从文件textes.html = overwrite content = No!
加载div antoine我喜欢把安东尼加到尼古拉斯身上 我喜欢添加尼古拉斯然后添加antone所以#right将是nicolas + antoine
我试图将内容变成var ... nope
任何想法?
除此之外......我想在每次加载时添加一条规则<hr>
也许这样的事情可以做到......它不起作用!
$('#right').load('textes.shtml #nicolas').append('<hr>').load('textes.shtml #antoine'); return false;
答案 0 :(得分:20)
也许我错过了一些东西,但似乎你们都错过了这是一个ajax调用的事实,你是在程序上调用函数而不是基于成功的ajax响应的回调函数。
此外,如果你正在做一些比将一些(X)HTML加载到元素更复杂的事情,你应该使用一个更强大的jQuery ajax方法(即get()或post()或ajax())
假设你在响应中得到(X)HTML:
// Only ONE ajax call and very simply parsing...
$.get('textes.html', {}, function(data) {
var $response = $('<div />').html(data);
var $nicolas = $response.find('#nicolas')
var $antoine = $response.find('#antoine');
$('#right').append($nicolas).append($antoine);
},'html');
这真的很简单。
答案 1 :(得分:8)
为什么不在一次通话中加载它们:
$('#right').load('textes.html #nicolas,#antoine');
修改的
受司法方式的启发,我想到了以下几点:
var $page = $('<div />').load('textes.html #nicolas,#antoine');
var $nicolas = $page.find('#nicolas');
var $antoine = $page.find('#antoine');
$('#right')
.html($nicolas)
.append('<hr/>')
.append($antoine);
这只会使一个(或两个,取决于firefox的感觉)调用服务器。从而节省带宽。但它也为你提供了更多的自由,如何插入元素和按顺序。
答案 2 :(得分:4)
以下是解决方案的完整源代码。
我在JSBin.com上托管了一个工作示例:http://jsbin.com/ulodu(可通过http://jsbin.com/ulodu/edit进行编辑)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<script>
$(function(){
$.get(
'http://jsbin.com/oyuho',
function(response){
/*
Wrap the response in a <div /> so that we can use
find() instead of filter(). Also remove <script> tags.
This is essentially what $.load() does.
*/
var responseWrapper = $('<div />').append(response.replace(/<script(.|\s)*?\/script>/g, ""))
$('#content')
.append(responseWrapper.find('#nicolas'))
.append('<hr />')
.append(responseWrapper.find('#antoine'));
}
);
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
答案 3 :(得分:1)
var nicolas = $('<div />').load('textes.html #nicolas');
var antoine = $('<div />').load('textes.html #antoine');
$('#right')
.append(nicolas.children())
.append('<hr />')
.append(antoine.children())
;
或者,Pim Jager的方式。
答案 4 :(得分:0)
请参阅appendTo功能。
答案 5 :(得分:0)
我得到了KyleFarris的真正简单答案
我甚至将它简化了一点,而且工作正常
向所有人致敬,这是最终的代码:
<script>
$.get('textes.shtml', {}, function(data) {
var $response = $('<div />').html(data);
$('#right')
.append($response.find('#nicolas'))
.append('<hr />')
.append($response.find('#antoine'));
},'html');
</script>