2017-08-29 53 views
3

我試圖使用clone(),我很接近,但我不能代替文字,它顯示兩個:如何在<br>之後設置文字樣式?

var td_clone = $('.ms-vb').clone(); 
 
$('span', td_clone).remove(); 
 
$('br', td_clone).remove(); 
 
var name = $.trim(td_clone.text()); 
 
$("td").append(name.toUpperCase());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<table> 
 
    <tr> 
 
     <td width="80%" style="padding-bottom: 3px" class="ms-vb"> 
 
      <span class="ms-announcementtitle"> 
 
       title is here 
 
      </span> 
 
      <br> 
 
      by hey 
 
     </td> 
 
    </tr> 
 
</table>

結果:

title is here 
by hey BY HEY 

雖然我期待:

title is here 
BY HEY 

jsFiddle here

+1

爲什麼你克隆的元素,當你似乎想要改變他們到位? – adeneo

+0

這是我發現在'
'之後發現文字的方式,如果你知道任何更好/更快的方法,請在答案上點燃 –

+0

無論如何,你做了一個克隆。您刪除跨度和跨度內的文本。然後刪除中斷,剩下的就是包含'by hey'的textNode。你把這個字符串,大寫,並將其附加到你已經有的HTML? – adeneo

回答

3

你」不正確地做,只是直接瞄準textNode

var node = document.querySelector('.ms-vb br').nextSibling; 
 

 
node.textContent = node.textContent.toUpperCase();
<table> 
 
    <tr> 
 
     <td width="80%" style="padding-bottom: 3px" class="ms-vb"> 
 
      <span class="ms-announcementtitle"> 
 
       title is here 
 
      </span> 
 
      <br> 
 
      by hey 
 
     </td> 
 
    </tr> 
 
</table>

多一點jQuery'ish是使用contents(),這實際上返回註釋和文本節點,但真的沒有必要爲此在平原JS解決方案非常簡單, jQuery版本包含幾乎相同的代碼來設置文本無論如何

$('.ms-vb').contents().each(function() { 
    if (this.nodeType === 3) 
     this.textContent = this.textContent.toUpperCase(); 
}); 
+1

而沒有jQuery需要 – j08691

+0

這將工作,如果只有一個
權利? –

+0

@ j08691不介意jQuery,因爲它被加載了其他的東西我得到了 –

0

這應該這樣做

var td_clone = $('.ms-vb').clone(); 
console.log(td_clone); 
$('span', td_clone).remove(); 
$('br', td_clone).remove(); 
var name = $.trim(td_clone.text()); 
$("td").append(name.toUpperCase()); 
+0

嘿看到你的更新,你真的測試過嗎?結果是完全按照問題代碼http://jsfiddle.net/Cba4m/39/ –

2

您需要從td先刪除文本,你可以做這樣的事情:

var td_clone = $('.ms-vb').clone(); 
 
var elements = $('.ms-vb').children(); 
 
$('span', td_clone).remove(); 
 
$('br', td_clone).remove(); 
 
$('.ms-vb').html(''); 
 
$('.ms-vb').append(elements); 
 
var name = $.trim(td_clone.text()); 
 
$("td").append(name.toUpperCase());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<table> 
 
    <tr> 
 
     <td width="80%" style="padding-bottom: 3px" class="ms-vb"> 
 
      <span class="ms-announcementtitle"> 
 
       title is here 
 
      </span> 
 
      <br> 
 
      by hey 
 
     </td> 
 
    </tr> 
 
</table>