首页 > 解决方案 > HTML标记:通过属性而不是通过将值作为孩子传递来编写元素textContent?

问题描述

我很确定这个问题的答案是否定的,但是,

有没有办法编写这样的 HTML 元素:

<button innerText="This is the button text" />

<!-- INSTEAD OF LIKE THIS: -->

<button>This is the button text</button>


对于这样的示例,我的请求似乎很笨拙,但是当您通过 ReactJS 返回多个看起来像这样的元素时,它更有意义。

<button
  className="btn"
  somePropA="Some Value"
  somePropB="Some Value"
  somePropC="Some Value"
  title="Some title"
>
  Some button innerText
</button>

<!-- VERSUS: -->

<button
  className="btn"
  somePropA="Some Value"
  somePropB="Some Value"
  somePropC="Some Value"
  title="Some title"
  innerText="Some button innerText"
/>

我希望能够为 , 等执行此button操作span

标签: javascripthtmlreactjsdom

解决方案


这可以使用 CSS 使用其伪元素attr()函数轻松完成,就像这样,您可以使用属性选择器定位任何元素。

对于自定义属性,假设使用data-*前缀,所以我在这里添加了它。

堆栈片段

[data-innerText]::before {
  content: attr(data-innerText);
}

/* specifically target span base element */
span[data-innerText] {
  display: inline-block;
  color: red;
  font-size: 20px;
  padding: 20px;
  letter-spacing: 10px;
  text-transform: uppercase;
}
<button data-innerText="This is the button text"></button>
<div>
  <span data-innerText="This is a span"></span>
</div>
<div>
  <button>And it only adds the text to elements that have the attribute set</button>
</div>


推荐阅读