删除’ ’ – 仍然在尝试
仍在寻找删除' '
从我的HTML代码中,在stackoverlow.com上找到了多种方式,但这些方法都没有工作!
HTML
No Space
1 Space
2 Spaces
3 Spaces
4 Spaces
jQuery的
$(document).ready(function() { $('p').text().replace(/ /g, ''); //$('p').html($(this).html().replace(/ /gi,'')); });
jsfiddle – 游乐场 http://jsfiddle.net/MrTest/hbvjQ/85/
任何帮助非常感谢。
皮特
您有代码而不是
$('p').each(function(){ $(this).html($(this).html().replace(/ /gi,'')); });
这个将取代每个空格字符:
$('p').text(function (i, old) { return old.replace(/\s/g, '') });
或者,如果您只想替换不间断的空格:
$('p').text(function (i, old) { return old.replace(/\u00A0/g, '') });
jsFiddle演示
我使用闭包作为.text()
的参数来设置新值。
请注意,HTML实体需要关闭;
到底。
尝试
$('p').each(function() { $(this).html($(this).html().replace(/ /g, '')); });
或者如果您想删除&nbsp尝试
$('p').each(function() { $(this).html($(this).html().replace(' ', '')); });
另请注意,空间是
而不是(你错过了;)
根据bažmegakapa的回答 ,这可以用于包含其他元素的元素。
$('p').html(function (i, old) { return old.replace(/ /g, '') });
.text()
摆脱了html元素; .html()
没有
这是一个非jQuery的答案,因为使用jQuery进行这样的任务是过度的,除非你已经将它用于你网站上的其他内容:
var p = document.getElementsByTagName('p'); Array.prototype.forEach.call(p, function(el) { el.innerHTML = el.innerHTML.replace(/ /gi, ''); });
No Space
1 Space
2 Spaces
3 Spaces
4 Spaces
您正在替换文本,但不会将其应用回来。 另外,使用$.trim
摆脱
$('p').text(function(i,e){ return $.trim(e.replace(/ /g, '')); });
这是代码:
$('p').each( function() { var elem = $( this ); elem.html( elem.html().replace( / /g,'' ) ); } );
这里是jsfiddle: http : //jsfiddle.net/hbvjQ/62/