【问题标题】:JavaScript: Getting HTML to appear inside of a var statement / functionJavaScript:让 HTML 出现在 var 语句/函数中
【发布时间】:2022-10-07 08:29:26
【问题描述】:

我知道这被问了很多,我已经尝试了一些来自 SO 的例子,但没有运气。

我有一个功能可以让我更改 div 中的文本并且它可以工作,但只能作为纯文本。我希望它作为 HTML 工作,但我尝试将其放入 innerHTML,可能是在错误的位置,并在我的脚本中用 + 符号分隔 HTML。似乎没有任何效果。要么我得到原始文本中的 HTML,要么该函数根本不起作用。

这是我此时的脚本:

$(function() {
  var copyStack = [
    \'<strong>This is bold text within strong tags,</strong>\' + \' this is the remainder of my copy.\',
    \'<strong>This is more bold text within strong tags,</strong>\' + \' this is the remainder of my second copy.\'
  ];
  $(\"#swatch-0\").click(function () {
     $(\".product-shop-description\").text(copyStack[0]);
     console.log(copyStack[0]);
 });
 $(\"#swatch-1\").click(function () {
     $(\".product-shop-description\").text(copyStack[1]);
     console.log(copyStack[1]);
 });
});
  • text 设置纯文本,而不是 HTML,请改用 html 方法。

标签: javascript


【解决方案1】:

我认为这就是你想要做的:

var copyStack = [
    '<strong>This is bold text within strong tags,</strong>' + ' this is the remainder of my copy.',
    '<strong>This is more bold text within strong tags,</strong>' + ' this is the remainder of my second copy.'
  ];
swatchOne = document.getElementById("swatch-0");
const changeInnerHTML = (elm, inner) => (elm.innerHTML = inner);
swatchOne.addEventListener("click", () => {
  changeInnerHTML(swatchOne,copyStack[0]);
});
swatchTwo = document.getElementById("swatch-1");
swatchTwo.addEventListener("click", () => {
  changeInnerHTML(
    swatchTwo,copyStack[1]);
});
.btn{
    background: #cecece;
    padding: 1em;
    width: max-content;
    margin-bottom:1em;
}
#swatch-0{
    background: #000;
    color:#fff
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./style.css">
</head>
<body>
    <div class='btn' id='swatch-0' >Hello</div>
    <div class='btn' id='swatch-1' >Hello22</div>
    <script src="./script.js"></script>
</body>
</html>

getElementById 属性用于访问 HTML 元素

更多信息 [这里][]

innerHTML 属性用于访问和修改 HTML 元素内部的 HTML

更多信息HERE

【讨论】:

  • 在我的情况下绝对行不通。可能对您有用,但文本必须直接替换 .product-shop-description 类中的任何内容。
  • 你能详细说明一下情况吗?
  • 实际上,我们已经弄清楚了。这是代码: $("#swatch-0").click(function () { $(".product-shop-description").html(copyStack[0]); console.log(copyStack[0]) ; });
【解决方案2】:

解决了!感谢一些帮助和一些猜测,这是答案:

$("#swatch-0-peanut-butter-chocolate-chip").click(function () {
 $(".product-shop-description").html(copyVariety[0]);
 console.log(copyVariety[0]);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-22
    • 2011-05-03
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    相关资源
    最近更新 更多