javascript - JS,使用 HTML 而不是变量

标签 javascript html css

我有一个“显示更多”按钮,它可以正常工作。我遇到的问题是,它使用来自 var text 的文本我希望它直接从 HTML 使用它,有什么建议吗?

var status = "less";

function toggleText() {
  var text = "TEST";

  if (status == "less") {
    document.getElementById("textArea").innerHTML = text;
    document.getElementById("toggleButton").innerText = "See Less";
    status = "more";
  } else if (status == "more") {
    document.getElementById("textArea").innerHTML = "";
    document.getElementById("toggleButton").innerText = "See More";
    status = "less"
  }
}
<div id="textArea">
  <!-- Here I want to implement HTML code and show it when clicked "See More"-->
</div>

<a id="toggleButton" onclick="toggleText();" href="javascript:void(0);">See More</a>

最佳答案

您可以简单地更改相关元素的 display CSS 属性

var status = "less";

function toggleText()
{
    
    if (status == "less") {
        document.getElementById("textArea").style.display = "block";
        document.getElementById("toggleButton").innerText = "See Less";
        status = "more";
    } else if (status == "more") {
        document.getElementById("textArea").style.display = "none";
        document.getElementById("toggleButton").innerText = "See More";
        status = "less"
    }
}
<div id="textArea" style="display: none;">
    Here I want to implement HTML code and show it when clicked "See More"
</div>


<a id="toggleButton" onclick="toggleText();" href="javascript:void(0);">See More</a>

关于javascript - JS,使用 HTML 而不是变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50192361/

相关文章:

javascript - 如何使用 selenium 在 python 中执行 Javascript 函数

java - 支柱 2 : Sending values of form fields from jsp to action class

php - 它不会总结,我的代码有什么问题?

javascript - 获取 Facebook 页面/个人资料 URL

javascript - 如何在jquery中同时访问整个数据表的一行

javascript - 如何删除样式元素中的 CSS 样式?

html - 为什么不定位: fixed add a footer on every page in print preview using media print css in Safari browser

html - 在 CSS/HTML 中为不同的屏幕尺寸设置自动高度和宽度

javascript - 如何在整个 DOM 中查询与某些计算样式匹配的元素? (纯js)

html - 样式无序列表以在圆 Angular 框中显示列表项