jQuery 如何将外部html加载到div中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19370417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:48:26  来源:igfitidea点击:

How to load external html into a div?

jqueryhtmlloadexternal

提问by user2660811

I've created this little code using jquery to load an external HTML file into my div, but it doesn't work, I'm running out of ideas. Any other jquery code works well. Any help appreciated:

我已经使用 jquery 创建了这个小代码来将外部 HTML 文件加载到我的 div 中,但它不起作用,我的想法已经用完了。任何其他 jquery 代码都运行良好。任何帮助表示赞赏:

<div id="zaladuj"> 
load external html file
</div> 
<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript"> 
    $('#zaladuj').click(function () { 
        $(this).load('s1.htm'); 
    }); 
</script> 

采纳答案by Fouad Fodail

You need to wrap your code within jQuery.ready()function since you have to wait for DOM to be fully loaded.

您需要将代码包装在jQuery.ready()函数中,因为您必须等待 DOM 完全加载。

<script type="text/javascript">
    $(document).ready(function(){
        $('#zaladuj').click(function () { 
            $(this).load('s1.htm'); 
        }); 
    });
</script>

回答by Maciej Treder

<script type="text/javascript"> 
    $('#zaladuj').click(function () { 
        $.ajax({
            context: this,
            dataType : "html",
            url : "s1.htm",
            success : function(results) {
                $(this).html(results);
            }
        });
    }); 
</script>