我正在开发一个脚本,但我不能使用 jQuery 库,所以我需要 JS 中的 .load() 等价物。
我需要在没有 jQuery 的情况下执行此操作:
$(document).ready(function(){
$('#a').click(function(){
$('body').append('<div id="b"></div>')
$('#b').load('x.html')
});
});
谢谢!
我正在开发一个脚本,但我不能使用 jQuery 库,所以我需要 JS 中的 .load() 等价物。
我需要在没有 jQuery 的情况下执行此操作:
$(document).ready(function(){
$('#a').click(function(){
$('body').append('<div id="b"></div>')
$('#b').load('x.html')
});
});
谢谢!
function load(url, element)
{
fetch(url).then(res => {
element.innerHTML = res;
});
}
function load(url, element)
{
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
load("x.html", document.getElementById("b"));
简单的答案是,如果没有像 jQuery 这样的库,您正在做的事情要正确完成相当复杂。这是“有效”的东西,但没有错误检查或跨浏览器完美。你真的可能不想要这个......但它就在这里。
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('a').addEventListener('click', function (e) {
e.preventDefault();
var div = document.createElement('div');
div.id = 'b';
document.body.appendChild(div);
var xhr = new XMLHttpRequest();
xhr.onload = function () {
div.innerHTML = this.response;
};
xhr.open('GET', 'x.html', true);
xhr.send();
}, false);
}, false);
</script>
</head>
<body>
<a id="a" href="#">load</a>
</body>
</html>
如果您想在没有 JS 的情况下执行此操作,我认为这会对您有所帮助,请在里面添加#b
<iframe src="x.html"></iframe>
function load(url, element)
{
fetch(url).then(res => {
element.innerHTML = res;
});
}
function load(url, element)
{
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
load("x.html", document.getElementById("b"));
这将加载“x.html”并将其放入元素中。
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
/* If you wanted post too */
// xmlhttp.open("POST", "/posturl", true);
// xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// xmlhttp.send("email=" + "value" + "&message=" + "value" + "&name=" + name"value");
xmlhttp.open("GET", "file_to_get.xml", true/* async, setting to false will block other scripts */);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.alert(xmlhttp.responseText);
}
}
<object type="text/html" data="my.html">
我发现 jquery 从加载的文件中加载运行脚本,将 innerHTML 设置为某些东西并不能解决问题......不要测试你是否可以在之后调用 init() 函数......