没有推测性解析错误的有效 xhtml 1.0 严格 JS 切换

Valid xhtml 1.0 strict JS toggle without speculative parsing error

我知道那里有大量的切换脚本,但到目前为止我找不到满足我需要的任何脚本。 应该是:

当在 JavaScript 部分中写入一些不完整的 html 时(例如标签未关闭),会发生推测性解析错误。

查看此示例,该示例在加载时导致推测性解析错误和内容闪烁:

function toggle(ID) {     
 var ele = document.getElementById(ID);
 
 if(ele.style.display == "block") {
   ele.style.display = "none"; } 
 else { 
   ele.style.display = "block"; } 
}
<a href="javascript:toggle('content')">Content Toggle Linktext</a>

<script type="text/javascript">
 /* <![CDATA[ */
 document.write('<div id="content" style="display:none;">');
 /* ]]> */
</script>

<p>Content blablabla</p>

<script type="text/javascript">
 /* <![CDATA[ */
 document.write('<\/div>');
 /* ]]> */
</script>

那么如何实现我的需求呢?也许我需要一种全新的方法? 谢谢,斯托尼

好的,我想我自己在 this blog comment 找到了一个解决方案,目前效果很好,使 html 更容易阅读。 脚本加载在 header.

/* JavaScript */
function toggle(ID) {   
    var ele = document.getElementById(ID);

    if (ele.style.display === "block") {
            ele.style.display = "none"; }
    else {
            ele.style.display = "block"; }
}

document.documentElement.className += " CssClassJsLoad";
// writes the classname "CssClassJsLoad" into the <html>-tag to make sure document is completely loaded by browser before parsing starts
/* CSS */
.CssClassJsLoad .JsHide {
    display:none; }
/* For all objects within both of these classes: Do not display.
Remember: the <html>-tag only gets the class "CssClassJsLoad" if JS is present or respectively successfully executed. So if JS is not present, display will be standard as "block" element */
<!-- HTML -->
<a id="content-link" href="javascript:toggle('content')">Content Toggle Linktext</a>

<div class="JsHide" id="content">
  <p>Content Text blablabla. Inherits class "JsHide" from surrounding div and "CssClassJsLoad" from surrounding html-tag</p>
</div>