[英]jquery and javascript toggle image tags between classes
I can not seem to get this right. 我似乎无法正确理解这一点。 Please help.
请帮忙。 The code is supposed to toggle the class of an img tag when a user clicks on a div.
该代码应该在用户单击div时切换img标签的类。
Here is the HTML 这是HTML
<li><img src="IMG/Gallery/val_day.jpg" id="img27" style="width: 100%;" alt="val_day" /></li>
</ul>
</div>
<p id="previousLink" href="#">«</p>
<p id="nextLink" href="#">»</p>
</div>
and here is my jQuery and Javascript. 这是我的jQuery和Javascript。
$(document).ready(function () {
var Gallery = {
li: [''],
picNum: 0,
nextPic: function () {
$('#nextLink').click(function () {
var $activeImg = "'#img" + Gallery.picNum + "'";
$($activeImg).toggleClass('activePic');
Gallery.picNum++;
$activeImg = "'#img" + Gallery.picNum + "'";
$($activeImg).toggleClass('activePic');
});
}
}
}); });
The problems I see are how the jQuery selectors are looking for images. 我看到的问题是jQuery选择器如何查找图像。
Remove the apostrophes. 删除撇号。 For example, change
var $activeImg = "'#img" + Gallery.picNum + "'";
例如,更改
var $activeImg = "'#img" + Gallery.picNum + "'";
to: 至:
var $activeImg = "#img" + Gallery.picNum.toString();
The same thing should be done with the second $activeImg. 第二个$ activeImg应该做同样的事情。
My other comment is on convention. 我的其他评论是关于惯例的。 By convention, in my experience, a variable representing a jQuery object should be prefixed with a $.
按照惯例,以我的经验,代表jQuery对象的变量应该以$开头。 $activeImg doesn't seem to be a jQuery object.
$ activeImg似乎不是jQuery对象。 It's a string.
这是一个字符串。 Use
activeImageSelector
instead (a suggestion). 请改用
activeImageSelector
(建议)。
Updated JS 更新了JS
$(document).ready(function () {
var Gallery = {
li: [''],
picNum: 0,
nextPic: function () {
$('#nextLink').click(function () {
var activeImageSelector = "#img" + Gallery.picNum.toString();
$(activeImageSelector ).toggleClass('activePic');
Gallery.picNum++;
activeImageSelector = "#img" + Gallery.picNum.toString();
$(activeImageSelector ).toggleClass('activePic');
});
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.