jQuery按钮单击更改图像 [英] jQuery button click change image
问题描述
$("#button").click(function () {
//debugger;
if ($("img[id=image][src:contains(Grass)]"))
$("img").attr({ src: "/Content/images/Spring.jpg", alt: "Spring" });
else
$("img").attr({ src: "/Content/images/Grass.jpg", alt: "Grass" });
});
<a href="/Content/images/Grass.jpg"><img src="/Content/images/Grass.jpg" alt="image" id="image"/></a>
<input type="button" id="button" name="button"/>
我有一个带有图像和按钮的简单表格,我希望在每个按钮上单击图像都可以更改.逻辑很简单.默认情况下,image src = /Content/images/Grass.jpg
当我单击按钮第一次更改图像时,但是当我单击第二次图像时,它不会变回来.我检入调试器,发现条件$("img[id=image][src:contains(Grass)]")
总是true
.但是在第一次单击按钮之后,它是否应该不为假?
I have simple form with image and button, i want on each button click image getting changed. The logic is very simple. By default image src = /Content/images/Grass.jpg
When i click button first time image getting changed, but when i am click second time it is does not changed back. I check in debugger and find out that condition $("img[id=image][src:contains(Grass)]")
always true
. But after first button click shouldn't it became false then?
如果我声明
var img1 = $("img#image[src:contains(Grass)]");
var img2 = $("img#image[src:contains(Grass2)]");
var img3 = $("img#image[src:contains(blabla)]");
每个img1.length = 1 img2.length = 1 img3.length = 1 为什么?
each img1.length = 1 img2.length = 1 img3.length = 1 Why?
但是
var img1 = $("img#image[src*='Grass']");
var img2 = $("img#image[src*='Grass2']");
var img3 = $("img#image[src*='blabla']");
每个img1.length = 1 img2.length = 0 img3.length = 0这是预期的结果.
each img1.length = 1 img2.length = 0 img3.length = 0 it is what was expected.
这是否意味着src:contains(text)
和src*=text
如此不同?
Does it means that src:contains(text)
and src*=text
is so different?
推荐答案
$("#button").click(function () {
var alt = ($('img#image[alt="Grass"]').length) ? 'Spring' : 'Grass';
$('img#image').attr({ src: "/Content/images/"+alt+".jpg", alt:alt });
});
<a href="/Content/images/Grass.jpg">
<img src="/Content/images/Grass.jpg" alt="Grass" id="image"/>
</a>
<input type="button" id="button" name="button"/>
这篇关于jQuery按钮单击更改图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!