简体   繁体   English

在jQuery中用另一个替换一组html br元素—用jQuery解析HTML

[英]Replace a set of html br elements with another in jQuery — parsing HTML with jQuery

So here's my problem. 所以这是我的问题。 I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. 我的网站上有一个第三方服务,可以从RSS feed生成一堆HTML,并在页面加载时粘贴到我的网页中。 However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. 但是,当生成HTML时,它会插入一堆完全不必要的break标签。 Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it. 不幸的是,生成此代码的源文件位于第三方服务器上,而不是我的服务器上,因此我无法对其进行调整。

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. 因此,我试图通过在body标签中的onLoad =“”属性内使用一个小的jQuery来调整页面加载之前的HTML。 However, I can't simply use something like $('br').remove(); 但是,我不能简单地使用$('br')。remove();之类的东西。 because then there aren't ANY break tags, and I need one per each spot where there are currently three. 因为那时没有任何break标签,而且我每个位置需要一个,目前有3个。

So ultimately, what I need to do is come up with a jQuery statement that replaces 因此,最终,我需要做的是提出一个jQuery语句来替换

<br><br clear=all><br>

with

<br />

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. 我对jQuery很陌生,但似乎找不到任何可以帮助我完成此任务的东西。 Any ideas? 有任何想法吗?

Thanks in advance for any help! 在此先感谢您的帮助!

Use the Next Adjacent Selector (+) : 使用下一个相邻选择器(+)

$("br+br").remove(); //Removes all <br> tags in front of another

jsFiddle demo jsFiddle演示

Assuming they are in the exact format you gave, you can do this: 假设它们的格式与您提供的格式完全相同,则可以执行以下操作:

var br = $('br[clear="all"]');
br.attr('clear', '');
br.prev('br').remove();
br.next('br').remove();

You can play with selector attributes, not inside the onload but inside the jquery ready (http://api.jquery.com/ready/) 您可以使用选择器属性进行播放,而不是在onload内部,而是在jquery就绪内部(http://api.jquery.com/ready/)

$('br[clear=all]').remove(); $( 'BR [清楚=所有]')除去();

more details on selector attribute:http://api.jquery.com/attribute-equals-selector/ 有关选择器属性的更多详细信息:http://api.jquery.com/attribute-equals-selector/

为什么不只替换RSS HTML容器的html:

  yourContainerElem.innerHTML =  yourContainerElem.innerHTML.replace(/<br><br clear=all><br>/gi, '<br />');

To remove all but one: 删除除一个以外的所有内容:

$('br,[clear!="all"]').remove()

Then to remove the 'clear=all': 然后删除“ clear = all”:

$('br').removeAttribute('clear')

You better do this with regexps not with jquery. 您最好使用regexps而不是使用jquery。 Simplest example: 最简单的例子:

string.replace('<br><br clear=all><br>', '<br />')

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

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