我有一个大致如下的布局:
<div id="foo">
<!-- a bunch of content -->
</div>
<div id="thumbnails">
<div class="thumb-content1"></div>
<div class="thumb-content2"></div>
<div class="thumb-content3"></div>
</div>
<div id="content-1">
<!-- some text and pictures, including large-pic1 -->
</div>
<div id="content-2">
<!-- some text and pictures, including large-pic2 -->
</div>
<div id="content-3">
<!-- some text and pictures, including large-pic3 -->
</div>
etc ....
在页面加载时,我想要显示'foo‘和’缩略图‘,并隐藏三个内容div。
当用户单击每个缩略图时,我希望隐藏foo,并将其替换为匹配的“content-x”。
我可以让我的头脑围绕jQuery显示,隐藏和替换(尽管,如果你想在你的例子中包含这些,加分!)。但是,我如何从缩略图类中提取并构造适当的内容id,然后将其传递给show hide代码呢?
发布于 2010-05-28 05:05:48
基于您的标记,您可以执行以下操作:
$("[id^=content]").hide();
$("#thumbnails > div").click(function() {
var id = $(this).attr('class').replace('thumb-content','');
$("#foo").html($("#content-"+id).html());
});
You can see a demo working here
这使用^=
starts-with selector隐藏初始div,单击时使用.html()
复制您想要的内容。
如果您有很多这样的<div>
,最好使用.delegate()
,它将单个事件处理程序而不是n
事件处理程序附加到每个可单击的<div>
。它看起来像这样:
$("[id^=content]").hide();
$("#thumbnails").delegate("div", "click", function() {
var id = $(this).attr('class').replace('thumb-content','');
$("#foo").html($("#content-"+id).html());
});
Demo updated for that here
发布于 2010-05-28 05:06:22
我只是使用了.each()
中的索引来构造id名称:
$("div[id^='content-']").hide();
$('#thumbnails').find('div').each(function(i,obj){
$(obj).click(function(e){
$("#foo").html($("#content-"+(i+1)).html());
});
});
你还可以看到一个working demo here (就拿那个...and吧!)
发布于 2010-05-28 07:49:44
Load Content by means of class and id
<meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.4.1");
google.setOnLoadCallback(function() {
// THIS IS WHAT YOU NEED (CALL IT ON LOAD)
$(function() {
$('.thumbs').click(function() {
var id = this.className.split(' ')[1];
$('#foo').html($('#' + id).html());
});
});
});
</script>
</head>
<body>
<div id="foo">
00 00 00
</div>
<div id="thumbnails">
<div class="thumbs content-1">Load 01</div>
<div class="thumbs content-2">Load 02</div>
<div class="thumbs content-3">Load 03</div>
</div>
<div id="content-1" style="display:none">
01 01 01
</div>
<div id="content-2" style="display:none">
02 02 02
</div>
<div id="content-3" style="display:none">
03 03 03
</div>
</body>
如果我没看错你的帖子,点击大拇指,你想把内容加载到#foo!如果这是正确的,请使用发布的示例:
$('.thumbs').click(function() {
var id = this.className.split(‘’)1;
$('#foo').html($('#‘+ id).html());
请注意,诀窍是让单击的元素具有与之对应的类名和包含所需内容的id元素。
希望这对你有帮助!
https://stackoverflow.com/questions/2924788
复制相似问题