2011-10-04 36 views
0

我有這樣的:JQuery的:我試圖文本之前刪除第一<br>,但每<br>被刪除

<p> 
<br> 
<br> 
JQuery problems again... 
<br> 
<br> 
Why me...? 
</p> 

我嘗試使用這樣的:

$("p").children(":first-child").nextUntil(":not(br)").remove(); 

但我莫名其妙地結束與此:

<p> 
JQuery problems again...Why me...? 
</p> 

據我瞭解,糾正我,如果我錯了,代碼搜索<p>的第一個孩子,這將是第一個<br>,然後刪除文本之前出現的所有。

我想要做的就是刪除出現在<p>元素中的文本之前的第一個<br>。你能告訴我我該怎麼做嗎?

+0

如果文本內包裹你現有的代碼將工作另一個元素(可能是'')。 – RoccoC5

+1

text在jQuery的'.next()'邏輯中不算作元素。 – jfriend00

+1

查看http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery查看如何獲取jQuery中的文本節點或將文本包裝在一個''所以jQuery將它看作一個元素。 – jfriend00

回答

0

它看起來像jQuery並沒有幫助很多,所以不是試圖強制它,這看起來像是一個普通的javascript(除了識別p標籤)的工作。這將適用於您的現有HTML,而無需在文本週圍添加<span>標籤。

$("p").each(function() { 
    var children = this.childNodes; 
    var removals = [], child, i; 
    for (i = 0; i < children.length; i++) { 
     child = children[i]; 
     // nodeType 1 is ELEMENT_NODE 
     if (child.nodeType == 1) { 
      if (child.nodeName.toLowerCase() == "br") { 
       removals.push(child); 
      } 
     } 
     // nodeType 3 is TEXT_NODE 
     else if (child.nodeType == 3) { 
      // stop at first non whitespace text node 
      if (child.nodeValue.match(/\S/)) { 
       break; 
      } 
     } 
    } 
    // now remove the nodes we collected for removal 
    // remove outside the first loop because childNodes is a live array 
    // and we don't want it changing while iterating it 
    for (i = 0; i < removals.length; i++) { 
     removals[i].parentNode.removeChild(removals[i]); 
    } 
}); 

你可以看到它在這裏工作:http://jsfiddle.net/jfriend00/NjaRF/

+0

非常感謝!它工作得很好。 – user969591

1

CSS選擇器永遠不會匹配文本本身只有元素。 jQuery對匹配文本節點沒有那麼多支持。我猜你必須做這樣的事情:如果你改變你的HTML這個

$("p").each(function() { 
    $($(this).contents()).each(function() { 
    if (this.nodeType === 3 && /\S/.test($(this).text())) { 
     // Found some text, so stop removing elements. 
     return false 
    } else if ($(this).is("br")) { 
     $(this).remove() 
    } 
    }) 
}) 
1

,其中文本是一個跨度:

<p> 
    <br> 
    <br> 
    <span>JQuery problems again...</span> 
    <br> 
    <br> 
    <span>Why me...?</span> 
</p> 

然後,您可以使用此jQuery來刪除這些領先
標籤:

$("p br:first-child").nextUntil(":not(br)").andSelf().remove(); 

看到它在這裏工作:http://jsfiddle.net/jfriend00/W2W5F/

+0

這是在Blogger上,我不能手動添加'span'到註釋。 – user969591

+0

然後,你就像在Daniel的例子中一樣手動搜索文本節點。如果您控制了HTML,我只是提供了不同的東西。 – jfriend00

+0

感謝您的幫助。 – user969591

0

我知道這是一個很老的問題,但我發現這個題目時,我今天遇到了類似的問題。

我找到一個替代 - 簡單 - 的解決方案,也許這將是有用的人:

$('p').each(function(){ 
    var h = $(this).html().trim(); 

    // remove <br> tags before text 
    while (h.match(/^<br ?\/?>/gi)) h = h.replace(/^<br ?\/?>/gi, '').trim(); 

    // remove <br> tags after text 
    while (h.match(/<br ?\/?>$/gi)) h = h.replace(/<br ?\/?>$/gi, '').trim(); 

    $(this).html(h);  
}); 

的jsfiddle演示:http://jsfiddle.net/ULwCL/

相關問題