Sharepoint Web部件中的外部Javascript文件

时间:2011-03-09 09:38:43

标签: javascript sharepoint-2010 web-parts

我正在创建一个sharepoint web部件,我想在其中调用外部javascript文件。我在以下位置创建了.js文件

C:\ Program Files \ Common Files \ Microsoft Shared \ Web Server Extensions \ 14 \ TEMPLATE \ LAYOUTS \ CustomJScripts

调用函数时,给定函数未找到错误。 javascript文件的位置是错误的吗? 以下是代码:

protected override void CreateChildControls()
{
    Page.ClientScript.RegisterStartupScript(
        this.GetType(), 
        this.ID, 
        "_spOriginalFormAction = document.forms[0].action;", 
        true);


       ClientScriptManager cs = Page.ClientScript;
        if (!cs.IsClientScriptIncludeRegistered("OnMouseOverScript"))
        cs.RegisterClientScriptInclude(
            this.GetType(), 
            "OnMouseOverScript", 
            ResolveUrl("/_layouts/CustomJScripts/MyJS.js"));
}

private void GetData(string strSchCode)
{

     Table t = new Table();

     TableRow tr = new TableRow();
     TableCell tc = new TableCell();

     tc.Attributes.Add("onmouseover", "return ShowInfo('AA');");
     tr.Controls.Add(tc);
     t.Controls.Add(tr);
     this.Controls.Add(t);
}

3 个答案:

答案 0 :(得分:0)

您必须将此javascript添加到您的webpart。在我的webpart中,我正在使用这种方法:

    protected override void OnPreRender(EventArgs e)
    {
        Page.ClientScript.RegisterStartupScript(GetType(), "MyScript",
            "<SCRIPT language='javascript' src='~/_layouts/CustomJScripts/MyJS.js'></SCRIPT>", false);
        base.OnPreRender(e);
    }

答案 1 :(得分:0)

单引号可能有问题吗?例如使用双引号而不是单引号:

tc.Attributes.Add("onmouseover", "return ShowInfo(\"AA\");");

答案 2 :(得分:0)

我会使用ScriptLink.Register方法,然后将文件移动到14 \ TEMPLATE \ LAYOUTS \ 1033 \ CustomJScripts。

ScriptLink封装了ClientScriptManager调用以及其他功能。 name参数是一个相对路径,这就是javascript文件需要位于14 \ TEMPLATE \ LAYOUTS \ LCID 目录中的原因(其中 LCID 是您的语言编号)。

您的代码看起来像这样:

protected override void CreateChildControls()
{
    Page.ClientScript.RegisterStartupScript(
        this.GetType(), 
        this.ID, 
        "_spOriginalFormAction = document.forms[0].action;", 
        true);

    ScriptLink.Register(this.Page, "CustomJScripts/MyJS.js", true);
}
相关问题