如何更改单选按钮的文本 [英] How to change the text of a radio button

查看:79
本文介绍了如何更改单选按钮的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单选按钮,需要从用户输入动态更新,但正常 .val() .text() .html()将无效。如何使用jQuery或纯JavaScript更改单选按钮的文本?

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?

推荐答案

单选按钮没有关联的文本用它。

A radio button doesn't have text associated with it.

但是如果你在无线电选项旁边有一个标签标签/ span标签。然后你可以使用 .next 来访问该元素并更改其 text / html

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

DEMO

HTML:

<input type="radio" /><label>Option 1</label>

<input type="radio" /><span>Option 1</span>

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;
    }
});

这篇关于如何更改单选按钮的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆