【问题标题】:JQuery load variable stored html into a divJQuery 加载变量存储的 html 到一个 div
【发布时间】:2013-03-08 14:01:53
【问题描述】:

朋友们,

我有一个简单的页面。我有一个 div(我们称之为 #content),其中包含我想要存储到变量中的内容(以 html 格式)。

<div id="content">
   <div id="left">
      <h1>Cool title</h1>
      <p>text</p>
   </div>
   <div id="right">
      <p>more text</p>
   </div>
</div>

然后我有一个通过 JQuery 绑定到点击函数的 div。单击时,它将#content 的内容存储到变量storedHTML 中,并将高度存储到storedHeight 中。然后它将#content的高度设置为0并删除#content中的html。

然后当再次点击它时,它会将高度动画化回storedHeight,比如说200px;它还会将 html 重新加载到 div 中。

问题在于将 html 重新加载到 div 中。我该怎么做呢?我试过了:

storedHTML = $('#content').html(); //to store it
$('#content').html(''); //to clear it 
$('#content').html(storedHTML); //to load it back up again

尝试加载它...但无济于事。

当我第一次编写它以从 p 标签中获取文本,将其最小化,然后再次放大时,这非常有效。例如:

storedText = $('p#example').text(); //to store it
$('p#example').text(''); //to clear it
$('p#example').text(storedText) //to load it back up again

出于此 html 加载的目的,我尝试使用 .html()、.text()、.data()、.load()。以及 .html() 和 .append() 的组合

我显然失败了。我不知道如何将 html(多个 div 等)加载回这个 div。我很想学习正确的方法!

感谢您一直以来的帮助朋友。

【问题讨论】:

  • 你能创建一个小提琴来说明这个问题吗? (这可能是 $(document).ready 相关问题
  • 我现在正在做小提琴。我认为这不是 document.ready 问题,变量 storedHTML 已在控制台中正确填充。以前使用这个,只有普通的.text(),工作正常......问题只是将html加载回div......

标签: jquery


【解决方案1】:

您是否尝试过使用 .hide() 和 .show()?

$('#content').hide();
$('#content').show();

您还可以在此处查看大量示例和文档: http://api.jquery.com/hide/

此外,即使您的方法不是最好的,它应该仍然有效。我不知道为什么 你遇到了问题,但下面的代码对我来说很好:

    <html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
</head>
<body>
<div id="content">
   <div id="left">
      <h1>Cool title</h1>
      <p>text</p>
   </div>
   <div id="right">
      <p>more text</p>
   </div>
</div>

<input type="button" value="Hide" onclick="hideContent()" />
<input type="button" value="Show" onclick="showContent()" />

</body>
<script type="text/javascript">
    var storedHTML = '';

    function hideContent() {
        storedHTML = $('#content').html();
        $('#content').html('');
    }

    function showContent() {
        $('#content').html(storedHTML);
    }

</script>
</html>

【讨论】:

  • 其实我没有!我认为这可能会奏效。然而,为了学习,我仍然很好奇,如何将存储在变量中的 html 加载到元素 (div) 中。
  • 查看我编辑的回复。将其粘贴到常规的 html 文件中并运行它。然后将其与您所拥有的进行比较。
猜你喜欢
  • 2012-06-23
  • 2017-09-17
  • 1970-01-01
  • 2015-05-23
  • 2012-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多