使用jQuery将元素后的文字换行 [英] Use jQuery to wrap text after element

查看:1050
本文介绍了使用jQuery将元素后的文字换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所拥有的:

标签内的复选框.

<label for="foo">
  <input type="checkbox" id="foo" />bar
</label>

我需要什么:

使用jQuery,我需要将复选框(即栏")后面的文本包装在span元素中.

Using jQuery, I need to to wrap the text following the checkbox (i.e. "bar"), in a span element.

<label for="foo">
  <input type="checkbox" id="foo" /><span>bar</span>
</label>

我尝试过的事情:

$('label').wrapInner('<span></span>');

这并不排除所需的复选框.

This does not exclude the checkbox as required.

推荐答案

如果要包装文本节点,则可以根据nodeType属性是否为3(即的值)来过滤元素的内容.一个文本节点),然后包装返回的文本节点.

If you want to wrap the text node, you could filter the contents of the element based on whether the nodeType property is 3 (which is the value of a text node), and wrap the returned text node.

$('label').contents().filter(function () {
  return this.nodeType === 3;
}).wrap('<span></span>');

或者,如果您知道文本节点将始终是input元素的下一个兄弟节点,则可以使用nextSibling属性选择下一个兄弟节点:

Alternatively, if you know the text node will always be the next sibling of the input element, you could select the next sibling node using the nextSibling property:

$('label input').each(function () {
  $(this.nextSibling).wrap('<span></span>');
});

这篇关于使用jQuery将元素后的文字换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆