gpt4 book ai didi

Jquery toggle()、hide() 未按预期工作

转载 作者:行者123 更新时间:2023-12-01 01:11:04 24 4
gpt4 key购买 nike

我刚刚开始在 Drupal 环境中使用 JQuery。

我有一些缩略图,我希望当您单击其中一个时,更大的图片会出现在“视口(viewport)”中(出现一个隐藏的 div)。可能有更好的方法来完成我正在做的事情,但我需要这样做。

这就是我所拥有的:

$(document).ready(function() {
//$('#bigpic1').hide(); //show the first big picture always on page load
$('#bigpic2').hide();
$('#bigpic3').hide();

$('a#thumb1').click(function() {
$('#bigpic2').hide(); $('#bigpic3').hide();
$('#bigpic3').toggle(200);
return false;
});
$('a#thumb2').click(function() {
$('#bigpic1').hide(); $('#bigpic3').hide();
$('#bigpic2').toggle(200);
return false;
});
$('a#thumb3').click(function() {
$('#bigpic1').hide(); $('#bigpic2').hide();
$('#bigpic3').toggle(200);
return false;
});

});

除了一些丑陋的代码之外,它也不能正常工作。当页面出现时,第一张大图片不会出现,单击更多缩略图会显示正确的 div - 但永远不会隐藏任何内容(“视口(viewport)”中一次应该只显示一张大图片)。

我的 HTML 看起来像这样

<table><tr>
<td><a href="#" mce_href="#" id="thumb1">...thumb1...</td>
<td><a href="#" mce_href="#" id="thumb2">...thumb2...</td>
<td><a href="#" mce_href="#" id="thumb3">...thumb3...</td>
</tr>
<tr><td colspan="3">
<!-- my "viewport" cell -->
<!-- the big picture displays here -->
<div id="bigpic1">... </div>
<div id="bigpic2">...</div>
<div id="bigpic3">...</div>
</td></tr></table>

最佳答案

# 选择器选择一个 ID,因此您不需要其中的类型。选择器是 jQuery 最好的功能之一,因此请更加熟悉它们。 http://api.jquery.com/category/selectors/ .

您甚至可以执行这样的通用方法(您需要为 元素指定名称)。

<table>
<tr>
<td>
<a href="#" mce_href="#" name="thumb1" id="thumb1">...thumb1...</a>
</td>
<td>
<a href="#" mce_href="#" name="thumb2" id="thumb2">...thumb2...</a>
</td>
<td>
<a href="#" mce_href="#" name="thumb3" id="thumb3">...thumb3...</a>
</td>
</tr>
<tr>
<td colspan="3">
<!-- my "viewport" cell -->
<!-- the big picture displays here -->
<div name="bigpic1" id="bigpic1">...1... </div>
<div name="bigpic2" id="bigpic2">...2... </div>
<div name="bigpic3" id="bigpic3">...3... </div>
</td>
</tr>
</table>

以及 jQuery 代码。

//on load
$(document).ready(function() {
$('#bigpic2').hide();
$('#bigpic3').hide();

//this will be run when an element has a name with the text "thumb" in it
$('[name*=thumb]').click(function() {
//hide all big pictures (loops over every element that has a name with the text "bigpic" in it
$('[name*=bigpic]').each(function(index, value) {
if ($(this).is(':visible')) { //if the big pic is visible
$(this).hide(200); //then hide it
return false; //found the visible big pic so no need to keep looping
}
});
//show the right image
$('#bigpic' + $(this).attr('id').replace('thumb', '')).show(200);
});
});// end on load

代码更少,可扩展性更强。如果您添加/删除图像,则不需要更改它。关于加载时显示的第一张图像,您是否在文档加载时尝试过 $('#bigpic1').show(); 。哦,您不需要在函数中返回值。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com