![](/img/trans.png)
[英]How do I use JQuery to swap images when clicked on anchor tag and outside element?
[英]swap yes and no images when either is clicked in html
我有兩個圖像“是”和“否”,單擊它們會更改顏色,它們會突出顯示。 單擊yes_unselect時,需要將其更改為yes_select並將id更改為no_unselect。 我面臨兩個問題。
1.單擊一次后,yes_unselect更改為yes_select,但再次單擊則不會更改回yes_unselect。
2.當yes_unselect更改為yes_select我想要id =“ no”圖像時,no_select更改為no_unselect。
<div id="yes">
<input type="image" src="images/yes_unselect.jpg" id="yes" onClick="if (this.src='images/yes_unselect.jpg') {this.src='images/yes_unselect.jpg';} else {if (this.src='images/yes_select.jpg') {this.src='images/yes_unselect.jpg';}}">
</div>
<div id="no">
<input type="image" src="images/no_select.jpg" id="no" onClick="if (this.src='images/no_select.jpg') {this.src='images/no_unselect.jpg';} else {if (this.src='images/no_select.jpg') {this.src='images/no_unselect.jpg';}}">
</div>
這樣的事情在頭上怎么樣:
var theAnswer = undefined; //Global variable for access later.
function changeAnswer(yes) {
theAnswer = yes;
//Yes should be a boolean, therefore true==yes, false==no
var eYes = document.getElementById('yes'),
eNo = document.getElementById('no');
eYes.src = ( yes ) ? 'images/yes_select.jpg' : 'images/yes_unselect.jpg';
eNo.src = ( yes ) ? 'images/no_unselect.jpg' : 'images/no_select.jpg';
}
當然,您將必須更改id
的沖突。 多個元素不能具有相同的id
,因此請將<div>
的id
更改為yesDiv
和noDiv
。
然后圖像的onclick
可以是changeAnswer(true);
為是按鈕和changeAnswer(false);
否按鈕。 腳本中的任何位置都可以訪問theAnswer
,它將反映用戶當前的選擇。
像這樣:
<script type="text/javascript">
function swap() {
var e_yes = document.getElementById("yes");
var e_no = document.getElementById("no");
var yes_unselect = 'images/yes_unselect.jpg';
var yes_select = 'images/yes_select.jpg';
var no_unselect = 'images/no_unselect.jpg';
var no_select = 'images/no_select.jpg';
var result = e_yes.src == yes_unselect;
e_yes.src = result ? yes_select : yes_unselect;
e_no.src = result ? no_unselect : no_select;
}
</script>
<div id="div_yes">
<input type="image" src="images/yes_unselect.jpg" id="yes" onclick="swap()">
</div>
<div id="div_no">
<input type="image" src="images/no_select.jpg" id="no" onclick="swap()">
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.