我有一个如下所示的div
<div class="registered-count-container">
<div class="registered-count-inner">@(spaceEvent.IsTeacherRegistered ? "Registered" : "Interested"): <span class="badge">@spaceEvent.RegisteredStudentCount/@spaceEvent.MaxClassSize</span></div>
</div>
我想要使用class&#39; registered-count-inner&#39;来更改div中的文本。没有删除“注册计数容器”内的范围&#39; div,但是当我像这样更改文本时
$(eventPanel).find(".registered-count-inner").text("Interested");
它清除了“注册计数内部”中的所有内容。 class包括带徽章类的span。有没有办法在不删除span标签的情况下更改文本?
答案 0 :(得分:2)
将该文字放在另一个范围内并仅更改:
<div class="registered-count-container">
<div class="">
<span class="registered-count-inner">@(spaceEvent.IsTeacherRegistered ? "Registered" : "Interested"):</span>
<span class="badge">@spaceEvent.RegisteredStudentCount/@spaceEvent.MaxClassSize</span>
</div>
</div>
然后是相同的代码:
$(eventPanel).find(".registered-count-inner").text("Interested");
答案 1 :(得分:0)
您可以在不修改标记的情况下执行此操作。使用jquery contents()
访问元素的子节点并替换第一个文本节点的文本(在标记中) - 请参阅下面的演示:
$('.registered-count-inner').contents().get(0).nodeValue = 'new text here';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="registered-count-container">
<div class="registered-count-inner">@(spaceEvent.IsTeacherRegistered ? "Registered" : "Interested"): <span class="badge">@spaceEvent.RegisteredStudentCount/@spaceEvent.MaxClassSize</span></div>
</div>
答案 2 :(得分:0)
因为您正在尝试替换div中存在的文本节点,所以您可以先过滤该文本节点元素,然后更改其内容。
var eventPanel = ".registered-count-container"
var textnode = $(eventPanel).find(".registered-count-inner").contents().filter(function() {
return this.nodeType === 3;
});
textnode[0].textContent = "Interested"
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="registered-count-container">
<div class="registered-count-inner">Registered <span class="badge"> I am span</span>
</div>
</div>
&#13;
答案 3 :(得分:0)
更灵活的方法
$(document).ready(function (){
replaceDivContent('.registered-count-inner', 'Registered', 'Interested');
});
function replaceDivContent(identifier, from, to){
var newContent = $(identifier).text().replace(from, to);
$(identifier).text(newContent);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="registered-count-inner">Registered: <span>Other Text Stuff</span></div>