javascript - 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
。
解决方案
这可以使用 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>
推荐阅读
- weblogic - 从 coherence 3.5 移动到 12.2.1.4 应用程序错误
- java - 在 Spring Boot 中验证参数而不抛出异常
- azure - 如何将角色添加到二头肌格式的资源组?
- c# - API 结果未按预期反序列化
- mongodb - 当过滤器数量庞大时,如何在 MongoDB 中创建索引?
- java - MySQL 更新需要更多时间与并发用户命中
- c# - 选择
- 来自 div/ul 的元素
- java - 我能否在 Azure 上为 Java 应用服务实施无代码 Application Insights?
- java - IntelliJ - Java - 从 github 拉取后缺少 src 文件夹
- angular - CanDeactivate 在 iFrame 中不触发