【问题标题】:Can I replace HTML text in an element by using vanilla JS as so? e.target.innerHTML.replace('old text', 'new text');我可以这样使用 vanilla JS 替换元素中的 HTML 文本吗? e.target.innerHTML.replace('旧文本', '新文本');
【发布时间】:2020-01-31 02:24:41
【问题描述】:
const tour = document.querySelector('.tour__heading');
const addSection = e => {
        e.target.innerHTML.replace('SHOW','red');
};
tour.addEventListener('click', addSection);

我可以使用 e.target 来改变上面的 HTML 文本吗?

【问题讨论】:

  • replace 不会就地更改字符串(字符串在 JS 中是不可变的)。您需要将innerHTML 设置为等于.replace() 的返回值

标签: javascript html innerhtml


【解决方案1】:

String.prototype.replace 函数将替换字符串的内容,但不会修改原来的内容。

你可以这样做:

e.target.innerHTML = e.target.innerHTML.replace('SHOW','red')

或者您可以为 HTMLElement 对象上的自定义函数创建一个 polyfill。

/* A polyfill for a custom HTML text replacer function */
if (HTMLElement.prototype.replaceHTML === undefined) {
  HTMLElement.prototype.replaceHTML = function(regexpOrSubstr, newSubstrOrFunc) {
    this.innerHTML = this.innerHTML.replace.apply(this.innerHTML, arguments)
  }
}

const tour = document.querySelector('.tour__heading')
const addSection = e => {
  //e.target.innerHTML = e.target.innerHTML.replace('SHOW','red')
  e.target.replaceHTML('SHOW','red')
}
tour.addEventListener('click', addSection)
.tour__heading:hover {
  cursor: pointer;
}
<div class="tour__heading">SHOW</div>

【讨论】:

    【解决方案2】:

    正如Nick Parson 提到的,String.replace() 是一个纯函数。它返回一个新值,但不会改变现有值。

    const initialText = 'initial';
    const changedText = initialText.replace('initial', 'changed');
    
    console.log(changedText);
    console.log(initialText);

    我建议改用textContent。因为您只想处理元素内的文本。更安全。


    const tour = document.querySelector('.tour__heading');
    const addSection = e => {
            const text = e.target.textContent;
            const updatedText = text.replace('SHOW','red');
            e.target.textContent = updatedText;
    };
    tour.addEventListener('click', addSection);
    <h1 class="tour__heading">
      SHOW
    </h1>

    【讨论】:

      猜你喜欢
      • 2011-10-11
      • 2019-06-07
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-25
      相关资源
      最近更新 更多