[英]How to update Label text that also contains an Input element
I am trying to update just the text within the label, but not touch the input value in any way. 我正在尝试仅更新标签内的文本,但不以任何方式触摸输入值。
<div id="shippingRates">
<label>
<input type="radio" name="shippingrate" class="shippingratequote" value="GUID1" />
Text I want to Update
</label>
<label>
<input type="radio" name="shippingrate" class="shippingratequote" value="GUID2" />
Random Text
</label>
</div>
Playing around in the console, this Javascript returns just the text of the label: 在控制台中播放,此Javascript仅返回标签的文本:
$('#shippingRates :input[value="GUID1"]').parent().text();
But what is happening is if I execute: 但是发生的是如果我执行:
$('#shippingRates :input[value="GUID1"]').parent().text("TEXT UPDATED!");
It overwrites the entire contents of the Label element, including the input element. 它会覆盖Label元素的所有内容,包括input元素。
How am I able to update just the text using jQuery/javascript? 如何使用jQuery / javascript仅更新文本?
EDIT: FYI, I am unable to make any changes to the HTML as it comes in from an external server-side function. 编辑:仅供参考,我无法对HTML进行任何更改,因为它是从外部服务器端函数传入的。
Thanks 谢谢
You can use the DOM to grab the text node following the input: 您可以使用DOM在输入之后获取文本节点:
$('#shippingRates :input[value="GUID1"]')[0].nextSibling.nodeValue= 'TEXT UPDATED!';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="shippingRates"> <label> <input type="radio" name="shippingrate" class="shippingratequote" value="GUID1" /> Text I want to Update </label> <label> <input type="radio" name="shippingrate" class="shippingratequote" value="GUID2" /> Random Text </label> </div>
Another way to do it... 另一种方式...
$('#shippingRates :input[value="GUID1"]').parent().contents().filter(function(){
return this.nodeType == 3;
})[1].nodeValue = "The text you want to replace with"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.