在ajax页面加载内容后加载jquery插件js

时间:2015-12-08 10:14:37

标签: javascript jquery ajax dynamic jquery-plugins

Foe示例,我有使用select2插件的页面:

function Initialize()
{
    if($('.su-tech').length) {
            $('.su-tech').select2({
                allowClear: true,
                width: '100%'
            });
    }
} 

和这样的HTML代码:

<select class="select2 su-tech" style="width:100%;">                                                    
    <option value="1" >option1</option>
    <option value="2" >option2</option>
    <option value="3" >option3</option>
</select>

我也用ajax用jQuery加载html内容:

    $(document).on("click", "#page1", function () {
        $.ajax({
            type: 'POST',
            url: "/example-page1",
            success: function (result) {
                $('.ajax_content').html(result);
                Initialize()
            },
        })
    })

现在我想动态加载jscss每个jquery插件:

<link rel="stylesheet" href="assets/vendors/select2/css/select2.min.css">

<script type="text/javascript" src="assets/vendors/select2/js/select2.min.js"></script>

1 个答案:

答案 0 :(得分:0)

试试这个

//Declare a script with id
<script type="text/javascript" id="pluginJS"></script>
$(document).ready(function () {
    $("#pluginJS").attr("src", "pluginJS.js");

    $("#pluginJS").load(function () {
        $("#otherJS").attr("src", "other-plugin.js");
    });
})

Ajax成功后调用

 $(document).on("click", "#page1", function () {
        $.ajax({
            type: 'POST',
            url: "/example-page1",
            success: function (result) {
                $('.ajax_content').html(result);

                //you can call JS Here
                $("#pluginJS").attr("src", "pluginJS.js");
                $("#pluginJS").load(function () {
                         //After Load PluginJS you can use jQuery
                         Initialize();
                });
            },
        })
})