如何在JSLink脚本中使用jQuery和jQuery UI(主要是可排序组件)。

到目前为止,我尝试了几种在JSLink脚本中动态加载JavaScript的方法,但我似乎无法达到工作。在Firefox Web Developer控制台中,它只是表示$未定义,未定义jQuery,并且未定义$ .ui。

有帮助吗?

解决方案

如果页面jslink在于未引用jQuery和jQuery UI脚本,则需要自己加载它们。这可以通过例如:

function loadScript(url, callback)
{
    // adding the script tag to the head as suggested before
   var head = document.getElementsByTagName('head')[0];
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = url;

   // then bind the event to the callback function 
   // there are several events for cross browser compatibility
   script.onreadystatechange = callback;
   script.onload = callback;

   // fire the loading
   head.appendChild(script);
}
.

在另一个javascript文件中包含一个javascript文件?

然后您使用它:

loadScript("url to jQuery", loadScript("url to jQuery UI", function (){
    // do your stuff here
});
.

但在我看来,我总是在我的页面上始终需要jQuery,所以我通过委托控制来添加:向SharePoint中的每个页面添加jQuery

在这种情况下,您可以使用

ExecuteOrDelayUntilScriptLoaded("jquery path", function(){
    // Your stuff here
});
.

其他提示

您可以使用JSLink属性加载多个文件。将URL包含到jQuery文件,并且您有一个很好的解决方法。请注意,您必须在同一Web应用程序中使用URL,您无法引用来自CDN或类似的库。

尝试这样的东西:

$Field.JSLink="~sitecollection/Style Library/MicrosoftAjax.js|~sitecollection/Style Library/jquery-1.7.2.min.js|~sitecollection/Style Library/YourTemplate.js" 
.

我通常使用类似于eirikb在他的评论中描述的变体:

if(typeof jQuery == 'function') 
    NotifyScriptLoadedAndExecuteWaitingJobs("jquery.js");
else if (LoadSodByKey('jquery.js', null) == Sods.missing) 
    RegisterSod('jquery.js', '//code.jquery.com/jquery-1.11.0.min.js');


SP.SOD.executeFunc("jquery.js", "jQuery", function () { 
    console && console.log("jquery loaded");
});
.

在jslink脚本中以开头

(window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.0.min.js"><\/script>'));
.

结果将是这样的。

(function () {
    (window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.0.min.js"><\/script>'));

    var overrides = {};
    overrides.Templates = {};

    overrides.Templates.Fields = {
        "FileLeafRef": {
            "NewForm": FillDefaultTitle
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrides);
})();
.

您需要确保用户可以访问'ajax.aspnetcdn.com / ...'位置。如果不是,您需要在SharePoint Envirnoment中托管jQuery文件。

许可以下: CC-BY-SA归因
scroll top