【问题标题】:How to add html text inside tag? [duplicate]如何在标签内添加html文本? [复制]
【发布时间】:2021-05-27 18:04:23
【问题描述】:

我想知道如何使用 javascript 在标签内添加 html 文本。不是可以使用 classList.add('') 或 setAttribute 添加的类或 id。 例如,我想在按钮标签内添加 html 文本“已禁用”,如下所示: <button class="button is-danger" id="reset">Reset</button><button class="button is-danger" id="reset" **disabled**>Reset</button>

javascript 的代码是什么?提前非常感谢您

【问题讨论】:

  • 那么你真正想要的是禁用按钮是对的吗?
  • 如果您为该属性设置值可以吗?喜欢btnEl.setAttribute("disabled", true)
  • 我不知道 disabled 是一个属性 - 非常感谢

标签: javascript html tags


【解决方案1】:

disabled 也是一个属性,即布尔属性。如果属性存在而与值无关,则如果存在任何布尔属性,则其值始终为真。 StackOverflow

const first = document.querySelector("#first");
const second = document.querySelector("#second");
const third = document.querySelector("#third");
const fourth = document.querySelector("#fourth");

second.addEventListener('click', () => {
  first.setAttribute('disabled', true);
})

third.addEventListener('click', () => {
  first.setAttribute('disabled', false);
})

fourth.addEventListener('click', () => {
  first.removeAttribute('disabled');
})
<button id="first"> Hello world </button>
<button id="second"> click to disable </button>
<button id="third"> click to disable </button>

<p> If you want to enable the button then you have to remove the attribute completely. Setting the value to false doesn't enable it</p>
<button id="fourth"> click to enable </button>

【讨论】:

    【解决方案2】:

    禁用也是一个属性。只写 disabled 和默认为 true 是一样的。disabled

    如果你想添加一个自定义属性来选择你可以并且应该在这里参考数据属性:custom attributes

    例如,您可以使用 setAttribute 本身通过简单的 dom 操作来添加这些属性。setting an attribute

    【讨论】:

      猜你喜欢
      • 2017-04-02
      • 2022-07-06
      • 2014-10-27
      • 2016-04-02
      • 2021-11-11
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      • 2017-09-15
      相关资源
      最近更新 更多