使用 jQuery 在元素后换行
Use jQuery to wrap text after element
我有:
标签内的复选框。
<label for="foo">
<input type="checkbox" id="foo" />bar
</label>
我需要的:
使用 jQuery,我需要将复选框后的文本(即 "bar")包裹在一个 span 元素中。
<label for="foo">
<input type="checkbox" id="foo" /><span>bar</span>
</label>
我尝试过的:
$('label').wrapInner('<span></span>');
这里不按要求排除复选框。
如果要换行文本节点,可以根据nodeType
属性是否为3(即文本节点的值)来过滤元素的内容,并且包装返回的文本节点。
$('label').contents().filter(function () {
return this.nodeType === 3;
}).wrap('<span></span>');
或者,如果您知道文本节点将始终是 input
元素的下一个兄弟节点,您可以 select 使用 nextSibling
属性:
$('label input').each(function () {
$(this.nextSibling).wrap('<span></span>');
});
我有:
标签内的复选框。
<label for="foo">
<input type="checkbox" id="foo" />bar
</label>
我需要的:
使用 jQuery,我需要将复选框后的文本(即 "bar")包裹在一个 span 元素中。
<label for="foo">
<input type="checkbox" id="foo" /><span>bar</span>
</label>
我尝试过的:
$('label').wrapInner('<span></span>');
这里不按要求排除复选框。
如果要换行文本节点,可以根据nodeType
属性是否为3(即文本节点的值)来过滤元素的内容,并且包装返回的文本节点。
$('label').contents().filter(function () {
return this.nodeType === 3;
}).wrap('<span></span>');
或者,如果您知道文本节点将始终是 input
元素的下一个兄弟节点,您可以 select 使用 nextSibling
属性:
$('label input').each(function () {
$(this.nextSibling).wrap('<span></span>');
});