问题
How do I change the "2 Year Subscription" to "2 year:" without losing the input field
<div class="radioOption subscription1Col3">
<input class="buyNow" type="radio" name="product2" value="6_0" checked="">2 Year Subscription</div>
回答1:
This is relatively simple, and I'd suggest the following (though currently untested):
var input = $('.radioOption.subscription1Col3 input'),
text = input[0].nextSibling.nodeValue,
newText = text.replace(/ subscription/i,': ');
input[0].nextSibling.nodeValue = newText;
JS Fiddle demo.
Or possibly this version might be preferred, since it leaves the adjusted text wrapped in a label
element, which aids UI and makes it easier to target that text content in future:
var input = $('#inputID'),
label = $('<label />',{'for' : 'inputID'})
.text(input[0].nextSibling.nodeValue.replace(/ Subscription/i,': '));
input.parent().empty().append(input, label);
JS Fiddle demo.
This does, though, require the input
to have an id
attribute so that the label
is semantically attached to that input
.
回答2:
Another way will be to change the textContent
$('.buyNow')[0].nextSibling.textContent = "New Content"
回答3:
jQuery doesn't support accessing text nodes, only elements, so you would need to use the DOM methods in Javascript to access the text node:
var nodes = $('.radioOption')[0].childNodes;
nodes[nodes.length-1].nodeValue= '2 Year';
Demo: http://jsfiddle.net/Guffa/PDqQW/
If you put an element around the text:
<div class="radioOption subscription1Col3">
<input class="buyNow" type="radio" name="product2" value="6_0" checked="">
<span>2 Year Subscription</span>
</div>
Then you can use just jQuery to access it:
$('.radioOption span').text('2 Year');
Demo: http://jsfiddle.net/Guffa/tRdYa/
来源:https://stackoverflow.com/questions/11411937/changing-text-after-an-input-field