I have the following HTML.
<p><img src="myimage.jpg" />This is my text</p>
And the following javascript to replace the spaces开发者_开发技巧 with Non-breaking spaces. This works fine except for the fact that it removes the image.
$("div.myDiv p").each( function() {
$(this).text( $(this).text().replace(/ /g, '\xA0'));
});
Any ideas how I can replace the spaces in the text and not alter the image.?
You need to check for the nodeType and replace only this value:
$(function() {
$("p").contents().each(function(i, e) {
if( e.nodeType === 3 ) {
e.nodeValue = e.nodeValue.replace(/ /g, '\xA0')
}
});
});
Example: http://www.jsfiddle.net/4yUqL/42/
No JavaScript needed for this.
<p><img src="myimage.jpg" />This is my text</p>
and in CSS
div.myDiv p {
white-space: nowrap;
}
Depending on your document structure, it might be useful to add an extra imgAndCaption
CSS class to your paragraphs where needed, and do:
p.imgAndCaption {
white-space: nowrap;
}
Why not put the text in a div and modify the text in the div ie:
<p><img src="myimage.jpg" /><div>This is my text</div></p>
$("div.myDiv p div").each( function() {
$(this).text( $(this).text().replace(/ /g, '\xA0'));
});
The image tag gets destroyed, because the img-tag is not included using text()
so i suggest you save the image first and prepend it after your replace
$("div.myDiv p").each( function() {
var $img = $(this).find('img:first');
$(this).text( $(this).text().replace(/ /g, '\xA0'));
$(this).prepend($img) ;
});
精彩评论