【问题标题】:dynamically insert javascript into <head> tag将 javascript 动态插入 <head> 标记
【发布时间】:2011-02-14 09:47:01
【问题描述】:

我正在使用 CEWP (webpart) 并将此代码放在那里。但这段代码不在&lt;head&gt; 标签内。我需要在&lt;head&gt;标签中插入这段代码,

<script src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">
$("*").each(function () { if ($(this).children().length == 0) { $(this).text($(this).text().replace('Respuesta','Responder')); } });
</script>

我该怎么做?此代码将如何在 CEWP webpart 中工作?

【问题讨论】:

    标签: javascript jquery sharepoint cewp


    【解决方案1】:

    首先,如果您将代码设置为在文档就绪时运行,则可以将代码放在&lt;head&gt; 中。

    但是,它仍然无法正常工作。您正在迭代 all 标记。包括&lt;html&gt;,这将是$('*')选择的第一个。

    因此,您阅读了&lt;html&gt; 元素内的所有文本(即整个文档文本),对其进行字符串替换,然后将其写回html text()。用一个简单的文本字符串替换 &lt;html&gt; 元素的所有先前文本和元素内容。从而破坏页面上的所有其他元素。哎呀。

    您要做的是找到每个文本节点并对其进行单独的字符串替换:

    $(document).ready(function() {
        $('*').each(function() {
            for (var i= this.childNodes.length; i-->0;) {
                var child= this.childNodes[i];
                if (child.nodeType===3) // TEXT_NODE
                    child.data= child.data.replace(/Respuesta/g, 'Responder');
            }
        });
    });
    

    (请注意,这里仍然存在许多可能的边缘情况,其中包含表单字段和其他元素,其中更改其中的文本可能无法达到您的预期。)

    【讨论】:

    • 你可以把 javascript 放在任何你想要的地方,但不要忘记 _spBodyOnLoadFunctionNames.push("myFunction")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 2013-04-22
    • 2010-10-23
    • 1970-01-01
    相关资源
    最近更新 更多