我的 JQuery 经验有限。非常感谢任何帮助。
我有一个包含 5 个列表项的无序列表。我有五张图片,我希望根据单击的列表项显示不同的图片。
示例:你今天吃了多少个苹果?选择 1 2 3 4 或 5。单击数字 5 将显示 5 个苹果的图像。
每张图片都将显示在同一张图片中,替换之前的图片。
选择需要在整个用户体验中“连续”进行。也就是说,用户需要能够根据需要选择 1 2 3 4 5 的次数。
我认为链接 5 个 If、Else 语句不是很有效吗?
这需要循环功能吗?
非常感谢
最佳答案
如果您确信每个列表元素都按顺序对应所需图像,则最原始的方法是使用索引。
示例: http://jsfiddle.net/w1xafnkg/
html:
<ul id="list">
<li>1 apple</li>
<li>2 apple</li>
<li>3 apple</li>
<li>4 apple</li>
<li>5 apple</li>
</ul>
<div id="images">
<img />
<img />
<img />
<img />
<img />
</div>
脚本:
var lastShown;
$('#list').on('click', 'li', function() {
var index = $(this).index();
if (lastShown)
lastShown.hide();
lastShown = $('#images img:eq(' + index + ')')
lastShown.show();
});
关于你的第二个问题:
示例: http://jsfiddle.net/w1xafnkg/1/
脚本
function initListToImageBind(defaultIndex) {
var lastShown;
if (!isNaN(defaultIndex)) {
lastShown = $('#images img:eq(' + defaultIndex + ')').show();
}
$('#list').on('click', 'li', function () {
var index = $(this).index();
if (lastShown) lastShown.hide();
lastShown = $('#images img:eq(' + index + ')')
lastShown.show();
});
}
/* invoking the function defined with the desired index number of image to
be shown by default */
initListToImageBind(4);
请记住,索引从 0 开始,假设您希望默认显示第三张图片,那么索引将为 2!!!
关于jquery - 单击某个链接以显示图像集合中的某个图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29189115/