我試圖與只圖像的複選框列表的形式和複選框圖片
我有這樣的代碼add an image to a html type input check box or radio:
<html>
<script type="text/javascript">
//global variables that can be used by ALL the function son this page.
var inputs;
var imgFalse = '52 0 ROff.png';
var imgTrue = '52 0 ROn.png';
//replace the checkbox with an image and setup events to handle it
function replaceChecks() {
//get all the input fields on the page
inputs = document.getElementsByTagName('input');
//cycle trough the input fields
for(var i=0; i<inputs.length; i++) {
//check if the input is a checkbox
if(inputs[i].getAttribute('type') == 'checkbox') {
//create a new image
var img = document.createElement('img');
//check if the checkbox is checked
if(inputs[i].checked) {
img.src = imgTrue;
} else {
img.src = imgFalse;
}
//set image ID and onclick action
img.id = 'checkImage'+i;
//set image
img.onclick = new Function('checkClick('+i+')');
//place image in front of the checkbox
inputs[i].parentNode.insertBefore(img, inputs[i]);
//hide the checkbox
inputs[i].style.display='none';
}
}
}
//change the checkbox status and the replacement image
function checkClick(i) {
if(inputs[i].checked) {
inputs[i].checked = '';
document.getElementById('checkImage'+i).src=getImageUnchecked(i);
} else {
inputs[i].checked = 'checked';
document.getElementById('checkImage'+i).src=getImageChecked(i);
}
}
function getImageChecked(input) {
if (input == 0)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
if (input == 1)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
}
function getImageUnchecked(input) {
if (input == 0)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
if (input == 1)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
}
function startImages() {
}
</script>
</html>
<head>
</head>
<body>
<input type="checkbox" id="option1" checked/> Test<br>
<input type="checkbox" id="option2" checked/> two<br>
<button onclick="alert('option 1 is checked? ' + document.getElementById('option1').checked
+ 'option 2 is checked? ' + document.getElementById('option2').checked)">Check</button>
<script type="text/javascript">replaceChecks();</script>
</body>
但僅適用於圖像啓動後顯示第一次點擊。 是否有任何解決辦法可以從頁面加載開始? 我嘗試了現有的功能,但什麼都沒有實現。
除非你希望你的HTML有一些點(可能性很小),則可以省略最後斜槓在您的元素被解析爲XML(''可以只是' ')。沿着同樣的路線,您不再需要在腳本標記中指定'type =「text/javascript」'。 –