如果存在嵌套的输入元素,则替换标签的文本

Bas*_*ass 5 html javascript jquery label

更改标签的文字似乎很简单:

var /**HTMLLabelElement*/ label = ...;
label.innerHTML = "...";
Run Code Online (Sandbox Code Playgroud)

或者,使用jQuery:

var /**HTMLLabelElement*/ label = ...;
$(label).text("...");
Run Code Online (Sandbox Code Playgroud)

如果标签包装<input/>元素,则上述任何一种都无法正常工作:

<label><input type="checkbox">Text</label>
Run Code Online (Sandbox Code Playgroud)

- 在这种情况下,<input/>元素将与旧文本一起替换.

如何更改标签的文本,而不影响其子元素?

Pra*_*lan 9

过滤掉非空文本子节点并将其替换为新内容.

$('label')
  // get all child nodes including text and comment
  .contents()
  // iterate and filter out elements
  .filter(function() {
    // check node is text and non-empty
    return this.nodeType === 3 && this.textContent.trim().length;
    // replace it with new text
  }).replaceWith('new text');
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="checkbox">Text</label>
Run Code Online (Sandbox Code Playgroud)


纯JavaScript方法

var label = document.querySelector('label');

// get all child nodes and update the text node from it
label.childNodes[2].textContent = 'new text'
// If you don't know the position 
// then iterate over them and update
// based on the node type
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="checkbox">Text</label>
Run Code Online (Sandbox Code Playgroud)

  • 很酷.有关更多参考,请参阅[nodeType](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType). (2认同)