[英]How to make image behave like a checkbox and send its value to backend
我想制作一個像復選框一樣的圖像。 (即圖片是一個綠色的椅子圖標,當你按下它時,它應該從綠色變成橙色,再次按下時,橙色變成綠色。)
以下代碼部分有效,當您單擊綠色圖標時,它會變成橙色,但是如果我再次單擊從橙色變為綠色,則什么也沒有發生,它會再次保持橙色
圖片:
<table style="width:70%">
<tr>
<th>
<center>0</center>
<img src="images/chairgreen.png" id="1" style="width:64px;height:64px;" onclick="if (src='images/chairgreen.png') { this.src='images/chairorange.png' } else if (src='images/chairorange.png') { this.src='images/chairgreen.png'}" >
</th>
</tr>
問題是onclick
方法,但我不知道如何修復它。 而且我也不知道如何將椅子的 id 和顏色發送到后端。 對於后端,我將使用 java spring。
您可以嘗試將類名定義為圖像的顏色。 然后您可以根據類名更改 src 屬性。 不要忘記在每次點擊時更改班級名稱。
function changeImg(img){ if(img.classList.contains("green")){ img.setAttribute("src","images/chairorange.png"); img.classList.remove("green"); img.classList.add("orange"); } else if(img.classList.contains("orange")){ img.setAttribute("src","images/chairgreen.png"); img.classList.remove("orange"); img.classList.add("green"); } }
<img src="images/chairgreen.png" id="1" class="green" style="width:64px;height:64px;" onclick="changeImg(this)">
當您附加點擊處理程序時,不要定義函數並運行多個語句。 如果您有復雜的事情,請編寫一個函數,然后觸發該函數。
<img src="images/chairgreen.png" id="1" data-src="green" style="width:64px;height:64px;" onclick="change();" >
<script>
function change(e){
const target = e.target;
const current = target.getAttribute('data-src');
switch(current){
case "green":
target.src= "images/chairorange.png";
target.setAttribute('data-src',"orange");
break;
case "orange":
target.src= "images/chairgreen.png";
target.setAttribute('data-src',"green");
break;
default:
console.error("error", e, current);
break;
}
}
</script>
但是如果你在腳本標簽中編寫,也可以在js中生成按鈕
const img = document.createElement('img');
img.setAttribute('src', "images/chairgreen.png")
img.setAttribute('id', "1") // use an iterator
img.setAttribute('data-src', "green");
img.style.height ="64px";
img.style.width = "64px";
img.addEventListener('click', change);
如果您通過 js 生成元素,您還需要附加到 DOM。
const body = document.querySelector('body');
body.appendChild(img);
if
只有 1 個等號,則您正在進行比較, if
至少需要 2 個等號進行比較。
onclick="this.src = (this.src == 'images/chairgreen.png') ? 'images/chairorange.png' : 'images/chairgreen.png'"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.