2010-09-03 55 views
2

好的,在您查看下面的代码之前,我知道它是AWFUL。这是多余的和臃肿,我不是要求任何人修复它:)jQuery链接/效率建议

我想知道我需要研究,以便自己解决它。我正在为我的女儿开发一个小型项目,这是一个交互式乘法表,可以在Mobile Safari中查看。

我想突出显示导致选定数字的单元格。所以,我创建了这个,我分享它,因为我想改进它,但我还没有足够的知识。

我需要研究哪些原则来改进这种功能?

您可以在这里看到了整个事情:http://dandenney.com/dev/jasmultiplication

的100(10×10)是什么,我想实现一个例子,但我想这样做的每一个数字:

// This starts base functionality of highlighting the involved numbers, 10x10=100 
$(document).ready(function() { 
    $(".tenxten").hover(function() { 
      $("td").addClass("non-choice"); 
      }, function() { 
      $("td").removeClass("non-choice"); 
    }); 
    $(".tenxten").hover(function() { 
      $(".twoxten, .threexten, .fourxten, .fivexten, .sixxten, .sevenxten, .eightxten, .ninexten").addClass("vertical-trail"); 
      }, function() { 
      $(".twoxten, .threexten, .fourxten, .fivexten, .sixxten, .sevenxten, .eightxten, .ninexten").removeClass("vertical-trail"); 
    }); 
    $(".tenxten").hover(function() { 
      $(".tenxtwo, .tenxthree, .tenxfour, .tenxfive, .tenxsix, .tenxseven, .tenxeight, .tenxnine").addClass("horizontal-trail"); 
      }, function() { 
      $(".tenxtwo, .tenxthree, .tenxfour, .tenxfive, .tenxsix, .tenxseven, .tenxeight, .tenxnine").removeClass("horizontal-trail"); 
    }); 
    $(".tenxten").hover(function() { 
      $(".vertical-ten, .horizontal-ten").addClass("choice"); 
      }, function() { 
      $(".vertical-ten, .horizontal-ten").removeClass("choice"); 
    }); 
});     
+0

我还没仔细研究过你的代码,但我认为你可以通过使用'.data()'方法使它更优雅,它允许你用任何匹配的元素存储任意数据。见http://api.jquery.com/data/ – 2010-09-03 02:28:55

回答

5

要获得10x10效果,您可以使用您悬停的行,<td>在其中的索引和.prevAll()既要得到的效果右侧的细胞,就像这样:

$(function() { 
    $("#multiplication").delegate("tr:gt(0) td:not(:first-child)", "hover", function() { 
    $(this).toggleClass("choice").prevAll().toggleClass("horizontal-trail") 
    .end().closest('tr').prevAll().find('td:nth-child('+($(this).index()+1)+')') 
            .toggleClass('vertical-trail'); 
    }); 
}); 

You can give it a try here,这只要使用.prevAll()获得该行的前面细胞应用水平一流。然后使用.end()我们回去$(this)(当前悬停的单元格),去到它的<tr>使用.closest(),再次证明使用.prevAll()之前获得的所有行,并使用.find():nth-child()让其中的同一指标在细胞中,然后添加或删除这些细胞上的课。

由于您只是打开和关闭,所以您可以使用一个悬停功能,该功能将映射到mousenetermouseleave并结合.toggleClass()。该.delegate()用途是在这里有一个悬停处理,而不是100

初始选择"tr:gt(0) td:not(:first-child)"是说没有在第一行,而不是最左边的细胞在其他行,所以这可以防止主号码从执行这个函数,所以它只会发生在表中。

+0

哇!真棒的东西...帽子了,先生... :) – 2010-09-03 02:50:35

+0

真棒!我很抱歉,我在回应方面如此落后,我以为我已经设置了电子邮件通知。 谢谢,有很多可以从中学习。 – 2010-09-03 22:14:05

+0

@丹 - 欢迎:)如果它解决了您的问题,请务必接受有关此问题和未来问题的答案:) – 2010-09-03 22:20:08

0

值得赞扬的项目。 :)

链接不一定会影响性能/效率,但选择器,我想。即使在设计时,一个元素可能有多个类名称,所以我会仔细地在矩阵上放置类,以便比现在少得多的hover。像所有的行都有一个共同的类,所有的列将有他们的共同类等