Javascript 使用AJAX和jQuery.get()从外部文档检索特定元素
使用ajax和jQuery,我试图在用户切换开关时从外部文档中的特定元素加载内容。目标内容由切换开关元素的Javascript 使用AJAX和jQuery.get()从外部文档检索特定元素,javascript,jquery,ajax,Javascript,Jquery,Ajax,使用ajax和jQuery,我试图在用户切换开关时从外部文档中的特定元素加载内容。目标内容由切换开关元素的名称指定 所以我从HTML开始 <input id="toggle1" name="externalContent1" class="toggle" type="checkbox"> <input id="toggle2" name="externalContent2" class="toggle" type="checkbox"> <input id="tog
名称
指定
所以我从HTML开始
<input id="toggle1" name="externalContent1" class="toggle" type="checkbox">
<input id="toggle2" name="externalContent2" class="toggle" type="checkbox">
<input id="toggle3" name="externalContent3" class="toggle" type="checkbox">
这是可行的,但它替换了#target
元素的内容。我需要追加而不是替换
然后我尝试了其他So的一些建议,使用.get()
但是这些使用.get()
、.post()
和.ajax()
的解决方案(至少以我尝试过的方式)不允许我在content.htm
中指定元素,它只会拉取整个文档
是否有方法使用.get()
从外部文档检索特定元素?
我一直在思考这个问题,我想我也可以在检索到的页面中搜索部分
,并仅附加该部分。我找到了,试过了,但我也没什么运气:
if ($(this).is(':checked')) {
$.ajax({
url: 'content.htm',
type: 'GET',
success: function(res) {
$(res.responseText).find(section).each(function(){
$('#target').append($(this).html());
});
}
});
}
只要稍加修改,就可以使用
.load()
解决方案。首先加载到单独的元素中,然后追加
if ($(this).is(':checked')) {
$('<div id="tempForLoad">').load("content.htm " + section, function(){
$('#target').append($('#tempForLoad').html());
$('#tempForLoad').remove();
});
}
if($(this).is(':checked')){
$('').load(“content.htm”+节,函数(){
$('#target').append($('#tempForLoad').html());
$(“#tempForLoad”).remove();
});
}
谢谢,这很有效。我想一个“黑客”解决方案就行了。你在($(“#tempForLoad')行中缺少了一个)
。remove();
说到那一行,为什么要用一组额外的括号括起来?我打算再给一天时间看看是否有人有其他建议,然后再标记你的答案。括号是一个打字错误,已修复。等待当然没问题。:)
if ($(this).is(':checked')) {
$.ajax({
url: 'content.htm',
type: 'GET',
success: function(res) {
$(res.responseText).find(section).each(function(){
$('#target').append($(this).html());
});
}
});
}
if ($(this).is(':checked')) {
$('<div id="tempForLoad">').load("content.htm " + section, function(){
$('#target').append($('#tempForLoad').html());
$('#tempForLoad').remove();
});
}