[英]Change the class of paragraph when radio button is clicked
我一直在使用以下代码根据选中的单选按钮更改<p>
的颜色。 我一直在使用红色和蓝色两个类,但它不起作用。
所以请帮助我。
<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>
因此,您的 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>
在香草 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);
}
});
或者,如果您使用 jQuery 并将其正确包含在您的页面中(在您的示例中并非如此):
$('document').ready(function() {
$('input:radio').on('change',function(){
$('#myParagraph').addClass(this.value);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.