简体   繁体   English

如何从 html 输入中获取属性值?

[英]How do i get attribute values from html inputs?

I have a radio button that looks like this:我有一个如下所示的单选按钮:

<input class="MCQRadio" id="MCQ" mcq-id="1" name="MCQ" question-id="1" type="radio" value="MCQ" /> MCQ

[EDIT] [编辑]

When i click the radiobutton, and several radio buttons have the same class name, how do i retrive the question-id value and mcq-id value from the specific button?当我单击单选按钮,并且几个单选按钮具有相同的 class 名称时,如何从特定按钮中检索 question-id 值和 mcq-id 值? Preferably with jQuery.最好用 jQuery。

I have already set up a click handler like this:我已经设置了一个这样的点击处理程序:

$(document).ready(function () {

    $('.MCQRadio').click(function () {
var mcq-id = $('#MCQ').attr("mcq-id");
var question-id = $('#MCQ').attr("question-id");
$('#MCQ').attr('question-id')
$('#MCQ').attr('mcq-id')

Most of the answers given already are correct.已经给出的大多数答案都是正确的。 I would make one addition to avoid traversing the DOM twice to find your radio button element.我会做一个补充,以避免遍历 DOM 两次来找到您的单选按钮元素。

//Store the jQuery object in a variable so that it's only retrieved once
var $myRadio = $('#MCQ');

//Get your attributes
var mcq-id = $myRadio.attr("mcq-id");
var question-id = $myRadio.attr("question-id");

You could also attach to the click event of all the radio buttons (by class selector) and grab the attributes in the event handler:您还可以附加到所有单选按钮的单击事件(通过 class 选择器)并在事件处理程序中获取属性:

$('.MCQRadio').click(function() {
    //Use $(this) to grab the attribute value of the selected element
    var mcq-id = $(this).attr('question-id');
    var question-id = $(this).attr('mcq-id');
});

The other answers already show you how to get the particular attributes.其他答案已经向您展示了如何获取特定属性。 But since you added in your edit that you want to get the attributes from the particular one that was clicked you can try:但是,由于您在编辑中添加了要从单击的特定属性中获取属性,您可以尝试:

$('.MCQRadio').click(function() {

   $(this).attr('question-id');
   $(this).attr('mcq-id');

});

These will return the values you want.这些将返回您想要的值。

$('#MCQ').attr('mcq-id')
$('#MCQ').attr('question-id')

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

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