jquery - 如何使用jquery替换<label>中的文本

标签 jquery

<label>
  Auto zoom 
  <input type="checkbox" class="js-switch" id="autoZoom" data-switchery="true" style="display: none;">
  <span class="switchery switchery-small" style="box-shadow: rgb(223, 223, 223) 0px 0px 0px 0px inset; border-color: rgb(223, 223, 223); background-color: rgb(255, 255, 255); transition: border 0.4s, box-shadow 0.4s;">
    <small style="left: 0px; transition: background-color 0.4s, left 0.2s;"></small>
  </span>
</label>

我上面有这段代码,我想将“自动缩放”替换为“测试”,我该怎么做?

$("#div label:contains('Auto zoom')").text("Test");

我尝试使用上面的代码,这显然不起作用,它也会删除后面的输入类型复选框...

最佳答案

最简单的方法是将文本包装在另一个元素中,例如 span,然后更改 text()

假设您无法更改 HTML,那么您可以通过使用 contents() 并检索第一个 textNode 来执行您需要的操作,如下所示:

var label = $('label').contents().filter(function() {
  return this.nodeType == 3 && this.nodeValue.trim();
})[0];

label.nodeValue = label.nodeValue.replace('Auto zoom', 'Test');
.switchery-small {
  box-shadow: rgb(223, 223, 223) 0px 0px 0px 0px inset;
  border-color: rgb(223, 223, 223);
  background-color: rgb(255, 255, 255);
  transition: border 0.4s, box-shadow 0.4s;
}

.switchery-small small {
  left: 0px;
  transition: background-color 0.4s, left 0.2s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  Auto zoom Foo Bar
  <input type="checkbox" class="js-switch" id="autoZoom" data-switchery="true" style="display: none;">
  <span class="switchery switchery-small">
    <small></small>
  </span>
</label>

另请注意,我将内联 style 属性移出了外部样式表中的规则。这要好得多,因为它可以整理 HTML 并将 HTML 与样式分开。

关于jquery - 如何使用jquery替换<label>中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44108441/

相关文章:

javascript - JS添加css类时如何应用css代码样式

javascript - 如果文本写入输入然后被删除,blur() 不起作用 - jQuery

javascript - .load 和 .getScript 之后的 jQuery 绑定(bind)仅在警报之后有效

jQuery AwesomeCloud 标签链接

jquery - Html 表格宽度自动扩展

javascript - 通过 jQuery 在悬停时暂停 setInterval

jQuery 性能 - 类选择器

JavaScript,按钮,点击

jquery - 如何清除 blueimp 的 jquery-fileupload 插件中先前选择的文件?

asp.net - ASP.NET 2.o 页面的 jQuery 登录模式弹出窗口