单击单选按钮时更改段落的类

时间:2014-04-08 09:37:56

标签: javascript-events radio-button

我一直在使用以下代码来更改

的颜色,具体取决于选中的单选按钮。 我一直在使用两个班级red&蓝色 但它不起作用

非常友好地帮助我

<html>
<head>
<script type="text/javascript">

var ele = document.getElementsByName('color');


    if (ele[0].checked) { //index has to be j.
          $("p").toggleClass("blue");
    }
    else {
            $("p").toggleClass("red");
    }


</script>

<style type="text/css">

.blue
{
color:blue;
}
.red
{
color:red;  
}
</style>

</head>

<body>

<input type="radio" name="color" value="blue">blue<br>

<input type="radio" name="color" value="red">red


<p>When a user clicks on a radio-button, it becomes checked, and all other radio-buttons         with equal name become unchecked.</p>



</body>
</html>

1 个答案:

答案 0 :(得分:0)

因此,您的javascript将在您的元素甚至存在于DOM之前执行。您应该将javascript代码放在正文的最末端,或将其包含在文档加载时触发的事件处理程序中。

HTML:

<input type="radio" name="color" value="blue">blue<br>
<input type="radio" name="color" value="red">red
<p id="myParagraph">When a user clicks on a radio-button, it becomes checked, and all other radio-buttons with equal name become unchecked.</p>

在Vanilla JS中:

document.addEventListener('DOMContentLoaded', function() {

   var radioButtons = document.getElementsByName('color');
   var paragraph = document.getElementById('myParagraph');

    for(var i=0;i< radioButtons.length;i++)
    {
        var elem = radioButtons[i];
        elem.addEventListener('change',function(e){     
            console.log(paragraph);
            if(paragraph.className)
                paragraph.className = this.value;
            else
                paragraph.classList.add(this.value);
        }
        ,false);

    }
});

Fiddle of this

或者,如果您使用jQuery并在页面中正确包含它(在您的示例中不是这种情况):

$('document').ready(function() {

    $('input:radio').on('change',function(){
        $('#myParagraph').addClass(this.value);
    });

});

Fiddle of this