2016-02-01 44 views
1

我嘗試將文本變成這樣的代碼:jQuery的文本替換成<a><span><span>文本</a>

<li> 
    <a id="toggle-edition" href="#"> 
     <span class="glyphicon glyphicon-pencil"></span> Edit page 
    </a> 
</li> 

隨着

$("#toggle-edition").text('Save Page') 

我跨度去除:(

+0

錯了,它不會取代舊的TAXT和引導渲染被改變。總是試試這個。此外,文本並未包含到跨度中,而是包含到鏈接元素中$ –

回答

1

我跨度被刪除是預期的行爲,因爲您正在覆蓋anchor的內容元件。

使用下面的代碼:

$("#toggle-edition > span")[0].nextSibling.nodeValue = 'Save Page';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a id="toggle-edition" href="#"> 
 
     <span class="glyphicon glyphicon-pencil"></span> Edit page 
 
    </a>

+0

舊文本沒有被替換,文本被包裹成跨度而不是錨點 –

+0

@MickaelBertainchant,請參閱更新的答案 – Satpal

0

你可以嘗試:

$("#toggle-edition").text('<span class="glyphicon glyphicon-pencil"></span> Save Page'); 
+0

應該告訴,而不需要重新構建span元素 –

1

jQuery是不是要文/註釋節點上運行。使用相關的純JS方法,如:

$("#toggle-edition > span")[0].nextSibling.nodeValue = "Save Page"; 

更多jQuery的一樣,它可能是:

$("#toggle-edition").contents().filter(function(){ 
    return this.nodeType === 3 && $(this.previousSibling).hasClass('glyphicon'); 
}).replaceWith('Save Page'); 
0

嘗試將此

$(document).ready(function() { 
      var gettextr = $("#toggle-edition"); 
      var oldVal = gettextr.text(); 
      var NewStr = $(gettextr).html().replace($.trim(oldVal), 'Save Page'); 
      $(gettextr).html(NewStr); 
     }); 
0

只是重置HTML內容

$(document).ready(function(){ 
     // save here your span element 
     var tmpChild = $("#toggle-edition>:first-child"); 

     // set into <a> element your span 
     $("#toggle-edition").html(tmpChild); 

     // enter new text value after your span 
     tmpChild.after('new Value') 

    }); 

所以你不會取代元素跨度,但這個span元素的新文本​​

看看這裏的工作代碼後插入: https://plnkr.co/edit/lAFCfVkN2DsvGA0GQmvn?p=preview

0

總結與跨度和ID的文字。所以,你可以使用$("#SpanID").html('Save page')更改文本,而不刪除以前的跨度

<a id="toggle-edition" href="#"> 
    <span class="glyphicon glyphicon-pencil"></span> 
<span id="SpanID"> Edit page </span> </a> 
相關問題