javascript 如何更改单选按钮的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9945748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the text of a radio button
提问by user1082764
I have a radio button that needs to be dynamically updated from user input but the normal .val()
, .text()
, and .html()
won't work. How can I change the text of a radio button using jQuery or plain JavaScript?
我有一个需要来自用户的输入,但正常进行动态更新单选按钮.val()
,.text()
以及.html()
将无法正常工作。如何使用 jQuery 或纯 JavaScript 更改单选按钮的文本?
采纳答案by Selvakumar Arumugam
A radio button doesn't have text associated with it.
单选按钮没有与之关联的文本。
But if you have a label tag / span tag
next to the radio option. then you can use .next
to access that element and change its text/html
但是如果你有一个label tag / span tag
旁边的收音机选项。然后您可以使用.next
访问该元素并更改其text/html
HTML:
HTML:
<input type="radio" /><label>Option 1</label>
or
或者
<input type="radio" /><span>Option 1</span>
JS:
JS:
var $label = $('input[type=radio]').next();
$label.text('Options');
Or you can use the below hack to change the text next to radio option. Note that the below code assumes that text is next to radio option.
或者您可以使用以下技巧来更改单选选项旁边的文本。请注意,以下代码假定文本位于单选选项旁边。
var isRadioLabel = 0;
$('div').contents().each(function() {
if (this.nodeName == '#text' && isRadioLabel == 1) {
isRadioLabel = 2;
}
if (isRadioLabel == 2) {
this.nodeValue = 'Options';
isRadioLabel = 0;
}
if (this.type == 'radio') {
isRadioLabel = 1;
} else {
isRadioLabel = 0;
}
});
回答by Naftali aka Neal
A radio input does not have text
无线电输入没有文本
All it is is this:
就是这样:
<input type="radio" />
回答by Facebook Staff are Complicit
If your <label>
has been properly associated with a particular radio button using the for
attribute (as it should be)...
如果您<label>
已使用for
属性(应该如此)与特定的单选按钮正确关联...
<form>
<input type="radio" id="example" />
<label for="example">Clickyclick</label>
</form>
...you can just search the DOM for it using by the for
attribute. Using jQuery:
...您可以使用for
属性在 DOM 中搜索它。使用jQuery:
<script>
var yourElement = $("#example");
var itsLabel = $("[for=" + yourElement.attr("id") + "]"); // <---
itsLabel.css("color", "red");
</script>
Try it in this fiddle.
试试这个 fiddle。