我想根据我输入的计数循环遍历 JQUERY。具体来说,如果我为条目 0 输入此内容,则此代码有效:
$(document).ready(function()
{
$('.0').mouseenter(function()
{
$('.hideme0').fadeIn('slow');
});
$('.0').mouseleave(function()
{
$('.hideme0').fadeOut('slow');
});
});
我现在希望用循环计数器替换 ('.0') 这是名称为 0 的动态 CSS 类 例如
for (var n = 0; n < 3; ++ n)
{
$(**n**).mouseenter(function()
{
$('.hideme**n**').fadeIn('slow');
});
$(**n**).mouseleave(function()
{
$('.hideme**n**').fadeOut('slow');
});
}
关于如何使用 jQuery 做到这一点有什么想法吗?我无法在 API 中找到信息,也无法通过 Google 搜索说明找到信息。
我希望这很清楚,并且您明白我想要做什么。
最佳答案
你没有得到什么?它只是一个简单的字符串,因此您可以通过连接来构建它:
$('.' + n).mouseenter(function()
{
$('.hideme' + n).fadeIn('slow');
//...
//and so on
但是,在 for 循环中使用它会因闭包而导致问题。你可以这样解决:
for (var n = 0; n < 3; ++ n)
{
(function(x){
$('.' + x).mouseenter(function()
{
$('.hideme' + x).fadeIn('slow');
});
})(n);
(function(x){
$('.' + x).mouseleave(function()
{
$('.hideme' + x).fadeOut('slow');
});
})(n);
}
Here is a working example使用您的 HTML(来自评论)
关于javascript - 使用循环编号作为键循环遍历 JQUERY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21334379/