我是JQuery(和JS)的新手。我试图做一个非常简单的事情,它将改变我的图像属性,由于某种原因,它不起作用。在过去的一个小时里,我一直在忽视这一点,我似乎找不到合理的原因,为什么它不起作用。我也尝试了$("#thumbnail-"+id).attr(...)
,但它不起作用。我无法弄清楚为什么。所以我把事情分解为下面的代码,仍然无法正常工作。由于某种原因,该属性不会改变。
这是我的代码(我评论它是为了让事情变得更轻松):
$(".innerImage").click(function (e) {
var imageName = ($(this).find('img').attr('src').split('/'))[2]; //returns something like 4.jpg
var id = (imageName.split('.'))[0]; //returns just 4 (from 4.jpg)
var thumb = "#thumbnail-"+id; //returns #thumbnail-4
var thumbnail = 'product/thumb/'+id+'.jpg'; //returns product/thumb/4.jpg
var full = 'product/full_size/'+id+'.jpg'; //returns product/full_size/4.jpg
$(thumb).attr('src', thumbnail); //This is the crazy part that doesn't work
alert(1); //Did a trace and it reached here.
});
有效的东西,但我不能使用它们:
所以这里奇怪的部分是以下工作:
$('img').attr('src', 'product/thumb/test.jpg');
$('#thumbnail-4').attr('src', 'product/thumb/test.jpg'); //this worked perfect. Notice how it's just that specific id, where I didn't concatenate the 4 using the method in my code. The latter is more general
然而,上面(后者)会弄乱我的所有图像而不是我想要的特定图像#thumbnail-id(其中id = 1,...)。可以任何指出我做错了什么。我唯一能看到的是它不允许我连接我的字符串并使用它们。
修改:HTML
<div id='imageArea-4' class='imageArea'>
<div class='leftSide'>
"<div class='innerImage'>
<img src='product/thumb/4.jpg' />
</div>
<div class='innerImage'>
<img src='product/thumb/4-002.jpg' />
</div>
</div>
<div class='rightSide' id='rightSide-4'>
<img id='thumbnail-4' src='product/thumb/4.jpg' />
<button class='zoomImg intense' data-image='product/full_size/4.jpg' id='zoomImg-4'></button>
</div>
</div>
答案 0 :(得分:2)
看起来正在发生的事情如下:
当您选择第一张图片4.jpg
时,id
会设置为4
。在这种情况下,您可以正确定位'#thumbnail-4'
。但是,当您点击第二张图片4-002.jpg
时,id
会设置为4-002
。因此,该脚本正在寻找更新不存在的#thumbnail-4-002
的来源。
我把这个小提琴放在一起以显示断开连接。 http://jsfiddle.net/fd2cwm8y/
我的建议是给thumbnail
一个唯一的ID,这样它就不依赖于你从点击后的图片中检索到的id
值,就像我在这里一起扔的那样:
http://jsfiddle.net/7qt8wzot/
我希望这有帮助!