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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:19:12  来源:igfitidea点击:

How to change the text of a radio button

javascriptjquery

提问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 tagnext to the radio option. then you can use .nextto access that element and change its text/html

但是如果你有一个label tag / span tag旁边的收音机选项。然后您可以使用.next访问该元素并更改其text/html

DEMO

演示

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.

或者您可以使用以下技巧来更改单选选项旁边的文本。请注意,以下代码假定文本位于单选选项旁边。

DEMO

演示

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" />

on and off radio inputs

打开和关闭无线电输入

回答by Facebook Staff are Complicit

If your <label>has been properly associated with a particular radio button using the forattribute (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 forattribute. 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