我有一个这样的下拉列表:
<form name="change">
<SELECT NAME="options" ONCHANGE="document.getElementById('frame1').src = this.options[this.selectedIndex].value">
<option value="">Choose</option>
<option value="stuff1.html">Stuff1</option>
<option value="stuff2.html">Stuff2</option>
<option value="stuff3.html">Stuff3</option>
</SELECT>
</form>
通过从列表中选择一个来将网页加载到iframe:
<iframe class="iframe" id="frame1" src="" scrolling="yes" frameborder="0"></iframe>
现在我希望它只加载具有名为cointainer1的ID的网页的特定部分。所有页面都有这一部分。这可能吗?我通过在每个URL之后插入#container1来尝试它,但是iframe的内容是可滚动的,因此网页的其他部分也是如此。将其更改为不可滚动对我来说不是解决方案。任何JavaScript解决方案? 提前谢谢。
答案 0 :(得分:1)
可能还有其他解决方案可以执行此操作,但我认为您可以将每个HTML页面的Container
内容加载到您的框架中
通过JavaScript pure遵循以下步骤:
1-应该创建一个函数来加载HTML页面XMLHttpRequest
,如:
var getHTML = function (url, callback) {
if (!window.XMLHttpRequest) return;
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (callback && typeof (callback) === 'function') {
callback(this.responseXML);
}
}
xhr.open('GET', url);
xhr.responseType = 'document';
xhr.send();
};
2-创建一个功能来处理您的选项更改事件,并通过传递getHTML
值来调用select
,如下所示:
function loadFram() {
var src = document.getElementById("opt1").value;
getHTML(src, function (response) {
var x = document.getElementById("frame1");
var y = (x.contentWindow || x.contentDocument);
if (y.document)y = y.document;
y.body.innerHTML = response.documentElement.querySelector('[id="Container"]').innerHTML;
});
}
3-我认为你的HTML代码是这样的,或者是这样的:
<form name="change">
<SELECT id="opt1" NAME="options" onchange="loadFram()" >
<option value="">Choose</option>
<option value="stuff1.html">Stuff1</option>
<option value="stuff2.html">Stuff2</option>
<option value="stuff3.html">Stuff3</option>
</SELECT>
</form>
<iframe class="iframe" id="frame1" src="" scrolling="yes" frameborder="0"></iframe>
尝试一下,你看到一切都很好。
但是您可以通过JQuery按照$.get
或$.ajax
的简化步骤来完成此操作
$('#opt1').change(function () {
var src = $(this).val();
$.get(src, function (data) {
var stuffContainer = document.createElement('div');
stuffContainer.innerHTML = data;
$('#frame1').contents().find('body').html($(stuffContainer).find('#Container').html());
});
}) ;
如果您想使用JQuery,请务必从HTML中删除onchange="loadFram()"
。
或者$.ajax
喜欢:
$(function () {
$('#opt1').change(function () {
var src = $(this).val();
$.ajax({
url: src,
dataType: 'html',
success: function (response) {
var stuffContainer = document.createElement('div');
stuffContainer.innerHTML = response;
$('#frame1').contents().find('body').html($(stuffContainer).find('#Container').html());
}
});
});
});
我更倾向于通过JavaScript提供纯解决方案,因为您没有标记JQuery,无论如何上述解决方案都能正常工作。