选择下一个功能

时间:2012-07-31 15:18:48

标签: javascript jquery

我的“#picknext”函数选择网格中的下一个单词拼写给用户。目前除了连续两次选择同一行之外,它还能完成它的工作。

我该如何防止这种情况?

$('#pickNext').mousedown(function() {
    // remove the class from all td's
    $('td').removeClass('spellword');
    // pick a random word
    rndWord = Math.floor(Math.random() * (listOfWords.length));

    // apply class to all cells containing a letter from that word
    $('td[data-word="' + listOfWords[rndWord].name + '"]').addClass('spellword');
});

HTML ...

<ul style="display:none;" id="wordlist">
  <li data-word="mum" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png"></li>
  <li data-word="cat" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://www.clker.com/cliparts/c/9/9/5/119543969236915703Gerald_G_Cartoon_Cat_Face.svg.med.png"></li>
  <li data-word="dog" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://www.clker.com/cliparts/e/9/4/1/1195440435939167766Gerald_G_Dog_Face_Cartoon_-_World_Label_1.svg.med.png"></li>
  <li data-word="bug" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://www.clker.com/cliparts/4/b/4/2/1216180545881311858laurent_scarabe.svg.med.png"></li>
  <li data-word="rat" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://www.clker.com/cliparts/C/j/X/e/k/D/mouse-md.png"></li>
  <li data-word="dad" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://www.clker.com/cliparts/H/I/n/C/p/Z/bald-man-face-with-a-mustache-md.png"></li>

2 个答案:

答案 0 :(得分:2)

您需要将rndWord变量存储在事件侦听器范围之外的某个位置(父作用域)或使用this.data('rndWord'),然后您可以看起来像

var r = rndWord;
while (r == rndWord) {
     rndWord = Math.floor(Math.random() * (listOfWords.length));
}

答案 1 :(得分:0)

不确定我是否理解正确但是......也许,大可能......

$('td[data-word="' + listOfWords[rndWord].name + '"]').not($(this)).addClass('spellword');