如何防止带有空格的JavaScript在WordPress中中断

How do I prevent JavaScript with whitespace from breaking in WordPress?

本文关键字:WordPress 中断 JavaScript 何防止 空格      更新时间:2023-09-26

我正在使用WordPress中的html/代码编辑器来插入一些JavaScript。由于我完全不明白的原因,这段代码不起作用:

<script type="text/javascript">
function onSubmit() {
    document.getElementById("result").innerHTML = "Hello innerHTML!";
}
</script>
<button onclick="onSubmit()">Say hello</button>
<p id="result">test</p>

而这段代码可以毫无问题地工作:

<script type="text/javascript">
function onSubmit() {
    document.getElementById("result").innerHTML = "Hello innerHTML!";
}
</script>
<button onclick="onSubmit()">Say hello</button>
<p id="result">test</p>

因此,函数调用前后的空白行会导致问题(在wordpress生成的html代码中,脚本标签被包含在段落锚点中)。显然,在浏览器中分别运行这两个脚本没有问题。

知道为什么这些空白行会导致此问题吗?如果没有一些空格,更长的脚本将难以辨认,恕我直言......

你必须要么

1)从脚本中删除所有空格和行返回符,这样WordPress就不会添加<p>标签,然后Javascript将起作用,正如您所发现的那样,或者

2)在帖子编辑器中禁用所有帖子/页面的autop(见 http://codex.wordpress.org/Function_Reference/wpautop),所以WP不添加段落分隔符,或者

3) 执行以下操作,这会使autop全局启用,但允许您在单个帖子和页面中使用 and 标签禁用它。

将下面的函数添加到函数中.php并使用两个标签

<!-- noformat on --><!-- noformat off -->

在您的页面/帖子编辑器中,即

    text will be rendered *with* autop
    <!-- noformat on -->
    text will be rendered *without* autop
    <!-- noformat off -->
    text will be rendered *with* autop

如前所述,两个格式标记之外的内容将启用自动。

添加到主题的功能.php:

// <!-- noformat on --> and <!-- noformat off --> functions
function newautop($text)
{
    $newtext = "";
    $pos = 0;
    $tags = array('<!-- noformat on -->', '<!-- noformat off -->');
    $status = 0;
    while (!(($newpos = strpos($text, $tags[$status], $pos)) === FALSE))
    {
        $sub = substr($text, $pos, $newpos-$pos);
        if ($status)
            $newtext .= $sub;
        else
            $newtext .= convert_chars(wptexturize(wpautop($sub)));      //Apply both functions (faster)
        $pos = $newpos+strlen($tags[$status]);
        $status = $status?0:1;
    }
    $sub = substr($text, $pos, strlen($text)-$pos);
    if ($status)
        $newtext .= $sub;
    else
        $newtext .= convert_chars(wptexturize(wpautop($sub)));      //Apply both functions (faster)
    //To remove the tags
    $newtext = str_replace($tags[0], "", $newtext);
    $newtext = str_replace($tags[1], "", $newtext);
    return $newtext;
}
function newtexturize($text)
{
    return $text;   
}
function new_convert_chars($text)
{
    return $text;   
}
remove_filter('the_content', 'wpautop');
add_filter('the_content', 'newautop');
remove_filter('the_content', 'wptexturize');
add_filter('the_content', 'newtexturize');
remove_filter('the_content', 'convert_chars');
add_filter('the_content', 'new_convert_chars');