如何防止带有空格的JavaScript在WordPress中中断
How do I prevent JavaScript with whitespace from breaking in WordPress?
我正在使用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');
相关文章:
- 在wordpress一定时间后更改自定义字段
- 如何使MailHandler.php在Wordpress中工作
- 高亮显示与数组字符串一起使用时文本插件中断
- Wordpress插件根据需要加载js和css
- 无法再创建Wordpress页面
- Wordpress中带有JQuery Accordion的未定义匿名函数
- 注意:wp_enqueue_script调用不正确.在 Wordpress 调试模式下
- Ajaxify Wordpress网站与社交插件
- AngularJS ui路由器html5模式中断路由
- 将js添加到wordpress中以突出显示css活动菜单
- 递归函数中断
- Wordpress:替换源(域名)链接
- Javascript-在文本区域中断,但不在段落中中断
- Wordpress中的Javascript出现匿名函数/引用错误
- 如何在WordPress的头中加载自定义jQuery
- 鼠标光标-用于wordpress网站
- .load ajax无法正常工作whitin wordpress主题
- 如何在没有插件和Wordpress的情况下创建共享社交媒体
- 在Wordpress中使用wp_enqueue_script中断脚本
- 如何防止带有空格的JavaScript在WordPress中中断