Javascript jQuery新闻项隐藏和折叠
我正在使用一个很好的脚本来隐藏和显示几个divJavascript jQuery新闻项隐藏和折叠,javascript,jquery,html,Javascript,Jquery,Html,我正在使用一个很好的脚本来隐藏和显示几个div // Catch all clicks on a link with the class 'link' $('.link').click(function(e) { // Stop the link being followed: e.preventDefault(); // Get the div to be shown: var content = $(this).attr('rel'); // Remo
// Catch all clicks on a link with the class 'link'
$('.link').click(function(e) {
// Stop the link being followed:
e.preventDefault();
// Get the div to be shown:
var content = $(this).attr('rel');
// Remove any active classes:
$('.active').removeClass('active');
// Add the 'active' class to this link:
$(this).addClass('active');
// Hide all the content:
$('.content').hide();
// Show the requested content:
$('#' + content).show();
});
这在一个有几个我喜欢隐藏的项目的单独div上非常有效
但是我使用一个模板来检索新闻条目,我喜欢在所有div individual上使用这个模板。默认情况下还隐藏第二个div
<div class="content" id="div[[+idx]]-1">
<p>Show content by default</p>
<a class="link-[[+idx]]" href="#" rel="div[[+idx]]-2">
Link to show div id="div[[+idx]]-2" and hide id="div[[+idx]]-1"
</a>
</div>
<div class="content hide" id="div[[+idx]]-2">
<p>Hide content by default</p>
<a class="link-[[+idx]]" href="#" rel="div[[+idx]]-1">
Link to show div id="div[[+idx]]-1" and hide div id="div[[+idx]]-2"
</a>
</div>
默认情况下显示内容
默认情况下隐藏内容
问题是我在每次迭代中都使用这个模板,脚本不支持未定义数量的项,并关闭所有其他div。第二个div在默认情况下不会隐藏
我将链接更改为link1,然后您会得到以下不需要的bahavior:
如果我省略了1,它什么也不做如果动态添加新的
.link
,则需要使用委派
通过使用,您可以侦听单击文档(或.link
的祖先元素,并在连接单击处理程序时出现),当触发单击时,它将查找.link
试试这个:
$(document).on('click', '.link', function(e) {
我建议您使用jquery提供的on方法来处理单击事件,经典的单击方法不适用于呈现DOM后创建的元素
$( "your-selector" ).on( "click", function() {
alert( "Hello world!");
});
使用.parent()文件
请看我的答案,您当前将告诉每个类为“content”的元素要隐藏。如果您只想要元素的子元素,那么需要通过parent()EDIT选择它:刚刚意识到您的链接实际上是要隐藏的div的子元素,所以您真正想要的是parent selector工具,谢谢这是一个很棒的工具,它在JSFiddle上进行了调整。现在,我只需要在默认情况下隐藏第二个div。
// Catch all clicks on a link with the class 'link'
$('.link').click(function(e) {
// Stop the link being followed:
e.preventDefault();
// Get the div to be shown:
var content = $(this).attr('rel');
// Remove any active classes:
$('.active').removeClass('active');
// Add the 'active' class to this link:
$(this).addClass('active');
// Hide all the content:
$(this).parent('.content').hide();
// Show the requested content:
$('#' + content).show();
});