问题
What I have:
A checkbox inside a label.
<label for="foo">
<input type="checkbox" id="foo" />bar
</label>
What I need:
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>
What I've tried:
$('label').wrapInner('<span></span>');
This does not exclude the checkbox as required.
回答1:
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>');
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>');
});
来源:https://stackoverflow.com/questions/34834061/use-jquery-to-wrap-text-after-element