【问题标题】:Is there a method to implement through data attributes in JavaScript?有没有一种方法可以通过 JavaScript 中的数据属性来实现?
【发布时间】:2020-10-23 10:20:08
【问题描述】:

我想在卡片展开时实现卡片内容,我已经使用 JavaScript 的帮助来实现标题、图像、描述,我使用 'data-title' 和 'data-type' 来显示标题和图像分别是工作正常,当我尝试使用 data-desc 属性实现卡描述时,它显示“未定义”。

请任何人帮助我编写代码。 我的代码链接:https://codepen.io/Avatar_73/pen/ExyNdMK

        const getCardContent = (title, type, desc) => {
            return `
                <div class="card-content">
                    <h2>${title}</h2>
                    <img src="./assets/${type}.png" alt="${title}">
                    <p>${desc}</p>
                </div>
            `;
        }
    <div class="cards">
        <div class="card" data-type="html" data-desc="I am HTML">
            <h2>HTML5</h2>
        </div>
   </div>

【问题讨论】:

  • 将代码的相关部分添加到您的问题中。了解如何创建minimal reproducible example
  • 是的,我已经更新了代码的具体块,你现在可以看看吗?谢谢...如果您想运行代码并检查,请使用 Codepen 链接。

标签: javascript html css custom-data-attribute


【解决方案1】:

在第 115 行,您忘记将 desc 传递给您的 getCardContent 函数

改为:

const content = getCardContent(card.textContent, card.dataset.type, card.dataset.desc)

【讨论】:

  • 非常感谢!我不知道我是怎么错过的。
【解决方案2】:

更改您的调用方法签名
 getCardContent(card.textContent, card.dataset.type)

getCardContent(card.textContent, card.dataset.type, card.dataset.desc)

您没有在方法中传递第三个参数(card.dataset.desc),因此它将值呈现为undefined

【讨论】:

  • 哦,非常感谢!我不知道我是怎么错过的。
猜你喜欢
  • 1970-01-01
  • 2013-01-09
  • 1970-01-01
  • 2015-04-17
  • 1970-01-01
  • 1970-01-01
  • 2023-01-30
  • 2020-04-08
  • 2021-08-14
相关资源
最近更新 更多