更新时间:2022-10-19 12:16:14
编辑:通过以这种方式使用< p>
标签, >目的,您应该尝试移除< br>
标签,并将文本放在< p>
元素,这些元素具有相同的效果,但在语义上是正确的。 我认为你
var $ p = $('。细节p');
$ p.contents()
.filter(function(){return this.nodeType == 3;})//选择所有文本节点
.wrap('< p>) //将它们放在段元素中
$('br',$ p).remove(); //删除所有中断元素
工作小提琴: http://jsfiddle.net/garreh/UWDw5/1/
This is what the HTML code looks like. I need to strip out the br tags and wrap the lines in paragraph tags (ie the lines with dates). Each date should be wrapped in its own paragraph tags.
<html>
<head><script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<h2>Other Events</h2>
<p>
<strong>Venue name</strong>
</p>
<div class="details">
<p>
Wednesday, May 11, 2011 <br>
Wednesday, June 08, 2011 <br>
Wednesday, July 13, 2011 <br>
Wednesday, August 10, 2011 <br>
Wednesday, September 14, 2011 <br>
Wednesday, October 12, 2011 <br>
Wednesday, November 09, 2011 <br>
19.00
<br>
</p>
</div>
</body>
</html>
I tried this block of jQuery code that I found after searching on Google, but it just doesn't work at all:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('body').html($('body').html().replace(/<br>\*/g,"</p><p>"));
});
I also tried this block of code, but instead of wrapping the dates in paragraph tags it put empty paragraph tags at the end of each line:
$(document).ready(function(){
$('.details p br').replaceWith('<p></p>');
});
This is how the HTML output looked. As you can see it hasn't wrapped the date lines with the p tags correctly:
<div class="details">
<p>
Wednesday, May 11, 2011 <p></p>
Wednesday, June 08, 2011 <p></p>
Wednesday, July 13, 2011 <p></p>
Wednesday, August 10, 2011 <p></p>
Wednesday, September 14, 2011 <p></p>
Wednesday, October 12, 2011 <p></p>
Wednesday, November 09, 2011 <p></p>
19.00
<p></p>
</p>
</div>
Does anyone know a way around this?
Edit: By using <p>
tags in that manner your runining it's whole purpose instead you should try removing the <br>
tags and placing the text inside <p>
elements, which will have the same effect but will be semantically correct.
Edit2: I think you wanted it in the above way, just triple read your question and I think I gotcha!
var $p = $('.details p');
$p.contents()
.filter(function() { return this.nodeType == 3; }) // Select all textnodes
.wrap('<p>') // Place them inside paragraph elements
$('br', $p).remove(); // Remove all break elements
Working fiddle: http://jsfiddle.net/garreh/UWDw5/1/