2016-06-13 75 views
-1
改變div的顏色

大家在計算器社區如何通過點擊特定的單選按鈕

我嘗試創建本地JavaScript的功能..... 我想改變的特定背景顏色invoice_wrapper格紅,如果我按一下按鈕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; ?> 

回答

0

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>

+0

玩這個代碼是我很難先生 – mohdadawe

+0

@mohdadawe,什麼是這樣的困難? – Rayon

+0

什麼是forEach你在這個函數中使用你的意思是循環 – mohdadawe