我需要相当于.load()的JS [英] I need the equivalent of .load() to JS

查看:80
本文介绍了我需要相当于.load()的JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个脚本,但是我不能使用jQuery库,所以我需要在JS中使用.load()。

I'm developing a script but I mustn't use jQuery library so I need the equivalent of .load() in JS.

我需要这样做没有jQuery:

I need to do this without jQuery:

$(document).ready(function(){

$('#a').click(function(){
   $('body').append('<div id="b"></div>')
   $('#b').load('x.html')
});

});

谢谢!

Thanks!

推荐答案

简单的答案是,你正在做的事情相当复杂,无法像jQuery这样的库来正确完成。这是有效的,但没有错误检查或跨浏览器完美。

The simple answer is you're doing things that are fairly complicated to get done correctly without a library like jQuery. Here's something that "works", but with no error checking or cross-browser perfection. You really probably don't want this... but here it is.

<!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>

这篇关于我需要相当于.load()的JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆