我嘗試將文本變成這樣的代碼: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')
我跨度去除:(
我嘗試將文本變成這樣的代碼: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')
我跨度去除:(
我跨度被刪除是預期的行爲,因爲您正在覆蓋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>
舊文本沒有被替換,文本被包裹成跨度而不是錨點 –
@MickaelBertainchant,請參閱更新的答案 – Satpal
你可以嘗試:
$("#toggle-edition").text('<span class="glyphicon glyphicon-pencil"></span> Save Page');
應該告訴,而不需要重新構建span元素 –
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');
嘗試將此
$(document).ready(function() {
var gettextr = $("#toggle-edition");
var oldVal = gettextr.text();
var NewStr = $(gettextr).html().replace($.trim(oldVal), 'Save Page');
$(gettextr).html(NewStr);
});
只是重置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
總結與跨度和ID的文字。所以,你可以使用$("#SpanID").html('Save page')
更改文本,而不刪除以前的跨度
<a id="toggle-edition" href="#">
<span class="glyphicon glyphicon-pencil"></span>
<span id="SpanID"> Edit page </span> </a>
錯了,它不會取代舊的TAXT和引導渲染被改變。總是試試這個。此外,文本並未包含到跨度中,而是包含到鏈接元素中$ –
這是因爲您正在替換「」標籤的內容。將代碼改爲'$(「Toggle-edition span」)。text(....);'我想你會得到你想要的。 –