【问题标题】:delete a part of a string (Javascript)删除字符串的一部分(Javascript)
【发布时间】:2015-08-31 20:25:08
【问题描述】:

如果我按下按钮,我试图删除部分文本。

所以我做了什么:

<div "topbar">
    hey there! <div class="close" id="topbar_search_close">remove this button</div>
</div>

和javascript:

document.getElementById("topbar").innerHTML -= '<div class="close" id="topbar_search_close">&times;</div><div class="search_main">';

还有其他选择吗?谢谢!

【问题讨论】:

  • -= 运算符是一个数字减法运算符。
  • 你到底想做什么?你不能减去字符串。您是要替换字符串,还是将其完全删除?
  • 您的 HTML 不完整:&lt;div "topbar"&gt;jsfiddle.net/m3esahgu
  • 我想删除字符串的第二部分。这样在按下按钮后,您就会听到“嘿!”

标签: javascript


【解决方案1】:

这应该从元素中删除所有子节点。

document.getElementById("topbar").empty();

如果您只是尝试更改文本并且您知道文本是什么。

document.getElementById("topbar").text = "some new text";

如果是不同的东西,那么请更具体地说明你想要什么。

【讨论】:

    【解决方案2】:

    要删除部分字符串,您可以像这样使用String.prototype.replace

    window.onload = function() {
      document.getElementById('topbar_search_close').addEventListener('click', function(e) {
        var topbar = document.getElementById('topbar');
        topbar.innerHTML = topbar.innerHTML.replace('<div class="close" id="topbar_search_close">remove this button</div>', '');
      });
    }
    <div id="topbar">
      hey there!
      <div class="close" id="topbar_search_close">remove this button</div>
    </div>

    但是删除 DOM 节点是个坏主意。您可以像这样简单地删除它:

    window.onload = function() {
      document.getElementById('topbar_search_close').addEventListener('click', function(e) {
        var node = e.target; //topbar_search_close
        node.parentNode.removeChild(node);
      });
    }
    <div id="topbar">
      hey there!
      <div class="close" id="topbar_search_close">remove this button</div>
    </div>

    【讨论】:

      猜你喜欢
      • 2012-03-31
      • 2012-01-21
      • 1970-01-01
      • 2017-05-11
      • 2018-12-07
      • 1970-01-01
      相关资源
      最近更新 更多