您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用jQuery解决动态加载页面中的重复对象?

如何使用jQuery解决动态加载页面中的重复对象?

以下函数将处理部分加载视图页面中的数据,并为脚本中的每个jQuery选择器添加指定的上下文。这个答案很好用。但是,它不支持外部脚本文件

function renderPartialView(control, data)
{
    // For detecting all script tag in loaded data.
    var reExtractScript = /(<script type="text\/javascript">)([\s\S]+?)(<\/script>)/gi;

    // For detecting all "$" sign (must be jQuery object) in loaded data.
    var reFindDollarSign = /\$\(([\S]+?)\)/gi;

    // Find all matched string in loaded data.
    var result = reExtractScript.exec(data);
    var allScript = '';

    if (result)
    {
        for (i = 0; i < result.length; i += 4)
        {   
            // Remove current script from loaded script.        
            data = data.replace(result[i], '');

            // Replace all "$" function by adding context parameter that is control.
            allScript += result[i+2].replace(reFindDollarSign, '$($1, "' + control + '")');
        }
    }

    // Load non-script html to control.
    $(control).html(data);

    // Evaluate all script that is found in loaded data.
    eval(allScript);
}

// This script will partially download view page from server in the same domain
$(function()
{
    $.get(getUrl('~/Profile/Section/ViewEducation'), null, function(data)
    {
        // When partial loading is complete, all loaded data will be sent to “renderPartialView” function
        renderPartialView('#education-view', data);
    });
});
JS 2022/1/1 18:15:47 有441人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶