堆叠流量社区的每个人都好
我尝试创建原生javascript函数..... 如果我单击radioyes按钮,我想将特定invoice_wrapper div的背景颜色更改为红色 如果我点击radiono按钮,则为绿色
我希望通过此关键字
执行此操作我怎么能通过原生javascript而不是任何图书馆来做到这一点
祝你好运..... <?php foreach($fetches AS $electricities): ?>
<div class="invoice_wrapper">
<?php if($electricities->paid == "Yes"): ?>
Yes: <input onclick="" class="radioyes" type="radio" name="paid" value="<?php echo $electricities->paid; ?>" checked>
No: <input onclick="" class="radiono" type="radio" name="paid" value="No">
<?php else: ?>
Yes: <input onclick="" class="radioyes" type="radio" name="paid" value="<?php echo $electricities->paid; ?>">
No: <input onclick="" class="radiono" type="radio" name="paid" value="No" checked>
<?php endif; ?>
</div>
<?php endforeach; ?>
答案 0 :(得分:0)
querySelectorAll
选择具有指定选择器的元素。:checked
选择器最初只会选择checked
元素来设置background
。Array.from
将Array-like-object
投射到array
Array#forEach
. classList.add/remove
与classes
var elems = document.querySelectorAll('.invoice_wrapper [type="radio"]');
var elemsInit = document.querySelectorAll('.invoice_wrapper [type="radio"]:checked');
var handler = function(elem) {
elem.parentNode.classList.remove('red', 'green');
if (elem.value === 'Yes') {
elem.parentNode.classList.add('green');
} else {
elem.parentNode.classList.add('red');
}
};
Array.from(elemsInit).forEach(handler);
Array.from(elems).forEach(function(elem) {
elem.addEventListener('change', handler.bind(null, elem));
});
.invoice_wrapper {
border: 5px solid black;
margin: 5px;
}
.green {
background: green;
}
.red {
background: red;
}
<div class="invoice_wrapper">
Yes:
<input class="radioyes" type="radio" name="paid1" value="Yes" checked>No:
<input class="radiono" type="radio" name="paid1" value="No">
</div>
<div class="invoice_wrapper">
Yes:
<input class="radioyes" type="radio" name="paid2" value="Yes">No:
<input class="radiono" type="radio" name="paid2" value="No" checked>
</div>