简体   繁体   English

jQuery更改所有<element> HTML如果HTML = Something

[英]jQuery Change All <element> HTML IF that HTML = Something

So essentially I have a ton of paragraph tags that contain non-breaking spaces. 所以基本上我有很多包含不间断空格的段落标签。 While I know, removing them and correcting the issue is the real concern - I'm working on a bandaid fix to auto-remove them after the page loads via jQuery. 虽然我知道,删除它们并纠正问题是真正令人担忧的问题 - 我正在制作一个bandaid修复程序,在页面加载后通过jQuery自动删除它们。

Essentially I have: 基本上我有:

<p>&nbsp;</p>

Several hundred times in a page. 一页几百次。

I want to remove them all via jQuery but of course not remove all the other paragraphs on the page which don't solely contain non-breaking spaces. 我想通过jQuery删除它们,但当然不会删除页面上不包含不间断空格的所有其他段落。

This should be fairly simple but for some reason I'm not getting it; 这应该是相当简单的,但由于某种原因,我没有得到它; something like: 就像是:

if($.trim($('p').html()) == '&nbsp;'){
$(this).remove();
}

That is only hitting the first paragraph on the page, I need to hit all of them. 这只是打到页面上的第一段,我需要点击所有这些。

jQuery can help you with that: jQuery可以帮助你:

$("p").html(function(index, oldHtml) {
    if (oldHtml === "&nbsp;") {
        $(this).remove();
    }
});

Live example 实例

That uses the variant of the jQuery html function that accepts a function . 它使用接受函数的jQuery html函数的变体 Add a $.trim if required. 如果需要,添加$.trim

Alternately: 交替:

$("p").each(function() {
  var $this = $(this);
  if ($this.html() === "&nbsp;") {
      $this.remove();
  }
});

Live example 实例

That uses each , and then html to retrieve the HTML of each element. 它使用each ,然后html来检索每个元素的HTML。 Again, add a $.trim if required. 如果需要,再次添加$.trim

Use jQuery's each() function to iterate over every one of them: 使用jQuery的each()函数迭代它们中的每一个:

$('p').each(function()
{
    if ($.trim($(this).html()) == '&nbsp;')
    {
        $(this).remove();
    }
}

You can also use the ":contains" selector to only get the paragraphs that contain a non-breaking space: 您还可以使用“:contains”选择器来仅获取包含不间断空格的段落:

$('p:contains("&nbsp;")')

Your selector is correct. 你的选择器是正确的。 But as soon as you call html() (or attr() or text() or anything like that) it just calls it for the first element matched. 但是只要你调用html() (或attr()text()或类似的东西)它就会调用它来匹配第一个元素。 So you have to iterate all the elements and test/remove each one of them 因此,您必须迭代所有元素并测试/删除它们中的每一个

$(p).each(function(){
  if($.trim($(this).html()) == '&nbsp;') {
    $(this).remove();
  }
});

如果他们都是这样我会使用正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM