javascript 如何动态禁用单选按钮组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15637572/
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-27 01:29:35  来源:igfitidea点击:

How to dynamically disable radioButton group

javascriptradio-button

提问by Jacob

I create one element in my radioGroup like this:

我在我的 radioGroup 中创建一个元素,如下所示:

var selectorLay1 = document.createElement('input');
        var selectorLay1Atributes = {
            'type': 'radio',
            'class': "selectorLay1",
            'id': "radioLay1",
            'name': "layouts",
            'onchange': "mv.createLayout(1,1)"};

I have different elements like this. But they all have the same name: 'layouts'. How to find all of this elements and disable them dynamically.

我有这样的不同元素。但它们都有相同的名字:'layouts'. 如何找到所有这些元素并动态禁用它们。

回答by Rohan Kumar

Try this:

试试这个:

var radios = document.getElementsByName('layouts');
for (var i = 0, r=radios, l=r.length; i < l;  i++){
    r[i].disabled = true;
}

Read https://developer.mozilla.org/en-US/docs/DOM/document.getElementsByNamefor getElementsByName

阅读https://developer.mozilla.org/en-US/docs/DOM/document.getElementsByNamegetElementsByName

回答by David says reinstate Monica

I'd suggest:

我建议:

var inputs = document.getElementsByName('layouts');
for (var i = 0, len = inputs.length; i<len; i++){
    inputs[i].disabled = true;
}

Simple demo.

简单的演示

This will select the relevant elements with the nameof layouts, and then, in the for {...}loop, iterate over those elements and set the disabledproperty.

这将使用nameof选择相关元素layouts,然后在for {...}循环中迭代这些元素并设置disabled属性。

Using a simple function approach:

使用简单的函数方法:

function disableByName(elName){
    var els = document.getElementsByName(elName);
    if (els !== null){
        for (var i = 0, len = els.length; i<len; i++){
            els[i].disabled = true;
        }
    }
}

var button = document.getElementById('radioDisable');

button.addEventListener('click',function(e){
    e.preventDefault();
    disableByName('layouts');
}, false);

Simple demo.

简单的演示

Or, if you'd prefer, you can extend the Object prototype to allow you to directly disable those elements returned by the document.getElementsByName()selector:

或者,如果您愿意,可以扩展 Object 原型以允许您直接禁用document.getElementsByName()选择器返回的那些元素:

Object.prototype.disable = function(){
    var that = this;
    for (var i = 0, len = that.length; i<len; i++){
        that[i].disabled = true;
    }
    return that;
};

document.getElementsByName('layouts').disable();

Simple demo.

简单的演示