我有一个格式化的文本字段,其中包含..
"this is some text node
<div class="myClass">contents....</div>
some more text node
<div class="myClass">contents....</div>
"
像这样。
现在我要移除所有周围的&#34;  
&#34;对那些只有class="myClass"
的那些div,即&#34;  
&#34;在那些div之前和之后。
我已经通过了这个链接,但它没有解决我的问题
jquery how to find if div with specific id exists
提前致谢。
答案 0 :(得分:3)
我可能会选择像
这样的东西var text = '"this is some text node <div class="myClass"> contents....</div> some more text node <div class="myClass"> contents.... </div> "';
var $ct = $('<div />', {
html: text
});
$ct.find('.myClass').each(function () {
if (this.nextSibling && this.nextSibling.nodeType == 3) {
this.nextSibling.data = this.nextSibling.data.replace(/^\s+/, '');
}
if (this.previousSibling && this.previousSibling.nodeType == 3) {
this.previousSibling.data = this.previousSibling.data.replace(/\s+$/, '');
}
})
var html = $ct.html();
演示:Fiddle
答案 1 :(得分:0)
你可以替换&#39;&#39;而不是&#39;&amp; NBSP;&#39;,
$('.myClass').html($('.myClass').html().replace(' ',''));
或尝试这样,
$('.myClass').html(function(i,h){
return h.replace(/ /g,'');});
答案 2 :(得分:0)
var text = '"this is some text node <div class="myClass"> contents....</div> "';
var $ct;
$ct = $('<pre />', {
html: text
});
$ct.find('.myClass').each(function () {
if (this.nextSibling && this.nextSibling.nodeType == 3) {
var r = this.nextSibling.data;
this.nextSibling.data = this.nextSibling.data.replace(String.fromCharCode(160), '');
var s = this.nextSibling.data;
this.nextSibling.data = this.nextSibling.data.replace(/^ /, '');
}
if (this.previousSibling && this.previousSibling.nodeType == 3) {
this.previousSibling.data = this.previousSibling.data.replace(String.fromCharCode(160), '');
this.previousSibling.data = this.previousSibling.data.replace(/ /, '');
}
})
var html = $ct.html();
alert(html);
感谢所有人。我刚刚修改了Arun P johny先生的代码。这对我来说非常有用。在他的代码中它也删除了空格,但我想删除&amp; nbsp only。