带有外部HTML文件的jQuery .before()(相同域名)

时间:2013-10-15 20:30:44

标签: javascript jquery html

我想知道是否可以在jQuery中使用.before()函数在同一个域中加载外部html文件。

我想要的是一个HTML表单,其中包含基于用户条目动态放置的表单元素(例如,可以添加尽可能多的电话号码字段)。我尝试了许多选项,如.load()或.html(),但我似乎无法找到任何有效的解决方案。也许我做得不对......

<script>
    $(document).ready(function(){
        $("#add_society_number").click(function(){
            $(this).closest('table').before(forms/society_phone_number.html);
        });
    });
</script>

我应该使用什么而不是“forms / society_phone_number.html”?

我会有很多共享表单的页面,这就是我希望它们出现在外部文件中的原因。

我想加载外部HTML文件的另一个原因是,当使用.before()函数时,我必须在代码中为每个换行符使用“\”...

谢谢:)

2 个答案:

答案 0 :(得分:0)

您需要使用$.ajax或其中一种辅助方法来获取内容。

$(document).ready(function(){
    $("#add_society_number").click(function(){
        var self = this;
        $.get("forms/society_phone_number.html",function(response){
            $(self).closest('table').before(response);
        });            
    });
});

答案 1 :(得分:0)

你也可以使用.load('/ url / to / script')

<script>
    $(document).ready(function(){
        $("#add_society_number").click(function(){
            $(this).closest('table tbody').load('forms/society_phone_number.html');
        });
    });
</script>