我正在尝试删除一个逗号而我似乎无法达到它,为什么?

nyh*_*r77 2 javascript jquery

看起来很简单,但我无法在HTML中使用逗号,只需将其从页面中删除即可.一定很容易,我很遗憾.谢谢您的帮助.

我的HTML代码段如下:

<div id="heightWeightContainer" class="inlineBlock"><span id="height" class="sans14 topData bold"></span>,</div>
Run Code Online (Sandbox Code Playgroud)

你会在行尾看到逗号.

我试过几种不同的方法来摆脱这个家伙.

$('#heightWeightContainer').html().replace(",","");
$('#heightWeightContainer').text().replace(",","");
$('#height').parent().text().replace(',','');
Run Code Online (Sandbox Code Playgroud)

我甚至尝试使用getElementById和.replace的纯JS,但似乎没有任何东西可以得到它.

我可以补充一点,这些代码行在控制台中工作,所以我不确定为什么它不会在我的js文件中.

我错过了什么?谢谢

Pra*_*lan 7

你只是用,返回的字符串替换而不做任何操作.您可以使用html() 回调函数来更新内容.'g'如果要删除所有匹配项,请添加全局标志

$('#heightWeightContainer').html(function(i, v) {
  return v.replace(",", "")
});
Run Code Online (Sandbox Code Playgroud)

或者您只能替换文本节点中的文本,这不会损害任何绑定到内部html元素的事件.使用contents()让孩子包括文本和注释节点.使用它迭代它们each()

$('#heightWeightContainer').contents().each(function () {
    if (this.nodeType == 3) {
        this.textContent = this.textContent.replace(',', '');
    }
});
Run Code Online (Sandbox Code Playgroud)

  • @nevermind:这将获取`heightWeightContainer`中的当前DOM结构,将其序列化为HTML并将其传递给完成`.replace()`并返回新HTML的回调.返回的HTML被解析并转换为新的DOM节点,取代现有的节点.如果有任何事件处理程序或与这些旧节点关联的其他数据,则所有数据都将被销毁.我知道这是OP的方法,但这是一个避免的解决方案. (2认同)