如何向 jQuery .each 函数添加闭包?
How to add a closure to jQuery .each function?
我有几个 link 和两个 class 是这样的:
<a href="#" class="button post-12">Babylon</a>
<a href="#" class="button post-47">Sumer</a>
<a href="#" class="button post-87">Ur</a>
我不希望这些按钮中的每一个都隐藏一个相关的 post,例如,单击带有 "post-12" 的 class 的 link 应该隐藏这个:
<p id="post-12">Babylon was an aicient city...</p>
为了做到这一点,我有这个 jQuery 脚本。但它始终是 post 和 id "post-87" 用所有三个按钮关闭。
var secondClass;
$('.button').each(function(){
secondClass = $(this).attr('class');
secondClass = secondClass.replace('button ','');
$(this).click(function(){
$('#'+secondClass+'').hide();
});
});
我在这里做错了什么?如何向 jQuery .each 函数添加闭包?
我认为我们可以在您的场景中利用 -data:
<a href="#" data-divid="post-12" class="button post-12">Babylon</a>
<a href="#" data-divid="post-47" class="button post-47">Sumer</a>
<a href="#" data-divid="post-87" class="button post-87">Ur</a>
$('.button').click(function(){
var divtoclose = $(this).data("divid");
$('#'+divtoclose).hide();
});
更改 secondClass 声明的范围:
$('.button').each(function(){
var secondClass = $(this).attr('class');
secondClass = secondClass.replace('button ','');
$(this).click(function(){
$('#'+secondClass+'').hide();
});
});
我有几个 link 和两个 class 是这样的:
<a href="#" class="button post-12">Babylon</a>
<a href="#" class="button post-47">Sumer</a>
<a href="#" class="button post-87">Ur</a>
我不希望这些按钮中的每一个都隐藏一个相关的 post,例如,单击带有 "post-12" 的 class 的 link 应该隐藏这个:
<p id="post-12">Babylon was an aicient city...</p>
为了做到这一点,我有这个 jQuery 脚本。但它始终是 post 和 id "post-87" 用所有三个按钮关闭。
var secondClass;
$('.button').each(function(){
secondClass = $(this).attr('class');
secondClass = secondClass.replace('button ','');
$(this).click(function(){
$('#'+secondClass+'').hide();
});
});
我在这里做错了什么?如何向 jQuery .each 函数添加闭包?
我认为我们可以在您的场景中利用 -data:
<a href="#" data-divid="post-12" class="button post-12">Babylon</a>
<a href="#" data-divid="post-47" class="button post-47">Sumer</a>
<a href="#" data-divid="post-87" class="button post-87">Ur</a>
$('.button').click(function(){
var divtoclose = $(this).data("divid");
$('#'+divtoclose).hide();
});
更改 secondClass 声明的范围:
$('.button').each(function(){
var secondClass = $(this).attr('class');
secondClass = secondClass.replace('button ','');
$(this).click(function(){
$('#'+secondClass+'').hide();
});
});