除了使用多行变量之外,还有其他方法可以存储HTML代码块吗?



因为我认为在var中使用多行字符串不是很方便。还有哪些其他方法可以解决这个问题?我不希望我的代码是这样的:

var str = "<p>'Hello World'</p>"+"<a href='www.blah.com'>click me</a>";

等等...

我需要这个,因为我希望 HTML 在 javascript 事件之后加载。我不想将转义字符用于引号,因为它会使代码有点不可读,特别是当您要对其进行更改时。

更新:

我不希望代码在页面加载的同时加载。将其设置为显示:无;然后显示:阻止;会减慢速度。

我的第一直觉是一个隐藏的元素,但我看到了关于不希望加载 html 的评论。
我的下一个想法是尝试使用XML <!CDATA[...]]>阻止隐藏元素,但测试表明这在HTML中不起作用。

这有一种令人难以置信的黑客感觉,但它可以工作(至少在我非常有限的测试中确实如此)。

<script id="str">/*
    <p>'Hello World'</p>
    <a href='www.blah.com'>click me</a>
 */</script>

使用 jquery 提取 html 并删除注释。

  var str = $("#str").html();
  str = str.slice(2, str.length-3).trim();

假设你有

<p id="message"> Hello World</p>

在你的CSS上,你会有:

#message
{
  display:none;
  /* other css*/
  }

在你的JavaScript上,你可以有这样的东西:

/* after some event or something */
document.getElementById("message").style.display = "block";

你觉得怎么样?

多亏了@drs9222我终于找到了一种方法来做到这一点。我将回答我自己的问题,以便未来的读者知道我为解决我的问题做了什么。也感谢@dandavis给我一个使用script type="text/plain"的想法。这是我的答案。

<!DOCTYPE html>
<html>
<head>
  <title>Testing</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
  <script type="text/plain" id="preCode">
    <h1>Hello World</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sit cumque nobis quo et ducimus. Porro, minima, facilis. Explicabo iure non optio quae! Eveniet dolore ex sunt nemo maiores eum voluptatum.</p>
  </script>
  <div class="insideHere">
    <!-- preCode will go inside here -->
  </div>
  <input id="clickMe" type="button" value="Click Me!" />
  <script>
    $('#clickMe').click(function() {
      $('.insideHere').append($('#preCode').html());
    });
  </script>
</body>
</html>

此代码不会妨碍加载除代码本身之外的其他元素。

相关内容

最新更新