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

时间:2015-09-12 18:44:36

标签: javascript jquery

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

我的HTML代码段如下:

<div id="heightWeightContainer" class="inlineBlock"><span id="height" class="sans14 topData bold"></span>,</div>

你会在行尾看到逗号。

我尝试了几种摆脱这个家伙的方法。

$('#heightWeightContainer').html().replace(",","");
$('#heightWeightContainer').text().replace(",","");
$('#height').parent().text().replace(',','');

我甚至尝试使用getElementById&amp; .replace似乎没有得到它。

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

我错过了什么?感谢

1 个答案:

答案 0 :(得分:7)

您只是替换了,而没有使用返回的字符串。您可以使用 html() 和回调函数来更新内容。如果要删除所有匹配项,请添加全局标记'g'

$('#heightWeightContainer').html(function(i, v) {
  return v.replace(",", "")
});

或者您只能替换文本节点中的文本,这不会损害任何绑定到内部html元素的事件。使用 contents() 来获取包含文字和评论节点的子项。使用 each()

对它们进行迭代
$('#heightWeightContainer').contents().each(function () {
    if (this.nodeType == 3) {
        this.textContent = this.textContent.replace(',', '');
    }
});