【问题标题】:I have an error in Javascript with an A href我在带有 A href 的 Javascript 中有错误
【发布时间】:2014-05-08 12:09:33
【问题描述】:

我不明白为什么这是一个问题。 有人可以解释这个问题,并且可能是一个可能的解决方案。 谢谢。

错误: 在此上下文中,XHTML 元素“a”不允许作为 XHTML 元素“脚本”的子元素

代码:

    <script type="text/javascript"> 
         // Andy Langton's show/hide/mini-accordion - updated 23/11/2009
         // Latest version @ http://andylangton.co.uk/jquery-show-hide

         // this tells jquery to run the function below once the DOM is ready
         $(document).ready(function() {

              // choose text for the show/hide link - can contain HTML (e.g. an image)
              var showText='More Info'; 
              var hideText='Less Info';

              // initialise the visibility check
              var is_visible = false;

              // append show/hide links to the element directly preceding the element with a class of "toggle"
             ***$('.toggle').prev().append(' (<a href="#" class="toggleLink">'+showText+'</a>)');***

             // hide all of the elements with a class of 'toggle'
             $('.toggle').hide();

             // capture clicks on the toggle links
             $('a.toggleLink').click(function() {

                    // switch visibility
                    is_visible = !is_visible;

                   // change the link depending on whether the element is shown or hidden
                   $(this).html( (!is_visible) ? showText : hideText);

                   // toggle the display - uncomment the next line for a basic "accordion" style
                   //$('.toggle').hide();$('a.toggleLink').html(showText);
                   $(this).parent().next('.toggle').toggle('slow');

                   // return false so any link destination is not followed
                   return false;

               });
         });
    <script>

【问题讨论】:

  • 您不能在脚本标签内放置锚标签。有点自我解释。
  • 将您的 XHTML 转换为 HTML5?
  • 你能围绕 class="toggle" 的内容发布 html 吗?
  • 尝试拆分标签:$('.toggle').prev().append(' (&lt;'+'a href="#" class="toggleLink"'+'&gt;'+showText+'&lt;/'+'a&gt;)');
  • 这个错误来自哪里?是来自某个验证者吗?在我看来,您的验证器不够聪明。您想要的任何 HTML 都允许在 javascript 字符串中。这个错误在我看来是假的。

标签: javascript jquery html xhtml


【解决方案1】:

HTML 和 XHTML 之间存在差异。在 XHTML 中,脚本没有 CDATA 内容类型:内容被视为与任何其他元素完全相同。这不仅仅是 NetBeans 的问题。

所以,有几种解决方案:

  • 将脚本放在一个单独的文件中,这样它的内容就不会被 XML 解析器破坏。这是最好的解决方案,因为它没有任何缺点。它适用于 HTML 和 XHTML。
  • 确保内容不包含任何&amp;lt;&amp;amp; 符号。还要确保编辑脚本以后不会引入&amp;lt;&amp;amp; 标志。将它们替换为它们的实体引用:分别为 &amp;lt;&amp;amp;
  • 如果脚本不包含]]&gt;,您可以将整个内容放在&lt;![CDATA[ .. ]]&gt; 块中。在某些浏览器中,这甚至可以在 HTML 中使用,但由于 &lt;![CDATA[ 并未正式定义为 HTML 标准的一部分,因此此方法(官方)与 HTML 不兼容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-06
    • 2014-06-08
    • 2015-08-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多