如何通过使用本机javascript单击特定单选按钮来更改div的颜色

时间:2016-06-15 10:25:41

标签: javascript php

堆叠流量社区的每个人都好

我尝试创建原生javascript函数.....我想将特定invoice_wrapper div的背景颜色更改为红色,如果我单击radioyes按钮或绿色,如果我单击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; ?>

1 个答案:

答案 0 :(得分:1)

<?php foreach($fetches AS $electricities): ?>

<div class="invoice_wrapper <?=$electricities->paid == "Yes" ? 'paid' : 'unpaid'?>">

<?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; ?>

请注意我添加的更改是<div class="invoice_wrapper" class="<?=$electricities->paid == "Yes" ? 'paid' : 'unpaid'?>">

然后添加以下css:

.paid {
  background-color: green; 
  //add the css you require for display
}

.unpaid {
  background-color: red;
  //css as required
}

在javascript中,如果要处理click事件,请编写一个函数,然后根据单击的值添加/删除付费/非付费类。

例如:

var yesRadios = document.getElementsByClassName("radioyes");

for (var i = 0; i < yesRadios.length; i++) {
    yesRadios[i].addEventListener('click', setPaid);
}

function findAncestor (el, cls) {
    while ((el = el.parentElement) && !el.classList.contains(cls));
    return el;
}

function setPaid(event) {
   //Note my pure js is a bit rusty so not sure if event.target is the right element to pass here, but do try it out or search for how to get the currently clicked element in event handler in javascript.
   var invoiceWrapper = findAncestor(event.target, 'invoice_wrapper');
   invoiceWrapper.className = "invoice_wrapper paid";
}