简体   繁体   English

使用javascript或prototype选择多个属性的html元素

[英]Selecting html element by multiple attributes with javascript or prototype

I have several html input elements which all look something like this: 我有几个html输入元素,看起来像这样:

<input id="1" type="radio" checked="checked" value="123" name="myinput" />

How do I fetch the input element with javascript by multiple attributes? 如何通过多个属性使用javascript获取输入元素? For instance I want to fetch the input element which is of type radio, is checked and have a value that equals 123? 例如,我想获取无线电类型的输入元素,检查并具有等于123的值?

Basically I want to do something like this (I know this doesn't work): 基本上我想做这样的事情(我知道这行不通):

var myElement = document.body.select('input[type=radio]:checked', 'input[value=123]');

使用原型,这应该可以工作:

$$("input[type=radio][id=1]:checked")

Here is a simple function that dose that. 这是一个简单的函数。

function getInput() {
    var elements = document.getElementsByTagName("input");
    for(var i=1, element=elements[0];element = elements[i++];) {
        if(element.type=="radio" && 
            element.checked==true && 
            element.id=="1") {
            return element;
        }
    }
    return null;
}

Change the if statement inside the loop to your liking. 根据自己的喜好更改循环内的if语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM