1

小さなパズル/記憶ゲームの場合、パズルの 2 つのピースを比較したいと考えています。それらが同じ(同じ文字を持っている)場合、私は警告したい(「一致」)。私は正しい道を進んでいると思いますが、変数の 1 つが範囲外のようです。コードのどこに配置すればよいかわからないためです。そのため、2 番目の部分が返されますが、最初の部分は未定義のままです。助けてください。とても感謝しています!

シャッフル & ショーをクリックし、その後 2 ピースをクリックすると、「未定義」ステートメントが表示されます。なぜ機能しないのか、何が機能するのか、そしてその理由を知りたい:P

HTML

<button id="shuffle">Show and Shuffle</button>

<div id="container">
   <div class="choices"><div class="letter">A</div></div>
   <div class="choices"><div class="letter">B</div></div>
   <div class="choices"><div class="letter">C</div></div>
   <div class="choices"><div class="letter">A</div></div>
</div>

JS

var amountofclicks = 0;
var firstcard = false;
var secondcard = false;

$('#shuffle').bind('click', function() {

    var divs = $("div.choices").get().sort(function() {
        return Math.round(Math.random());
    }).slice(0, 16);

    $(divs).appendTo(divs[0].parentNode).show();

});

$('.choices').bind('click', function() {

    if (amountofclicks < 2) {
        amountofclicks++;
        $(this).unbind('click');
        if (amountofclicks == 1) {
            firstcard = true;
            var txt = $(this).find('.letter').text();

        }

        if (amountofclicks == 2) {
            secondcard = true;

            var txt2 = $(this).find('.letter').text();
            alert(txt + ' ' + txt2);


        }

    }

});

問題のあるJSFIDLLE

4

2 に答える 2

3

txt2回目のクリックで読み取れるように、変数を関数の外に移動する必要があります。このようなもの:

var amountofclicks = 0;
var firstcard = false;
var secondcard = false;
var txt; // store here

var次に、最初に値を設定する行からを削除する必要があります。

if (amountofclicks == 1) {
    firstcard = true;
    txt = $(this).find('.letter').text(); // note: 'var' removed
}

ワーキングフィドル


見苦しい外部変数を使用する代わりにdata、最初のカードの値を持つコンテナに属性を設定することもできます。たとえば、次のようになります。

if (amountofclicks == 1) {
    firstcard = true;
    $("#container").data('first-letter', $(this).find('.letter').text());
}

if (amountofclicks == 2) {
    secondcard = true;

    var txt = $("#container").data('first-letter');
    var txt2 = $(this).find('.letter').text();
    alert(txt + ' ' + txt2);
}

フィドルの例

于 2012-12-20T14:42:13.503 に答える
1

最初のコードは問題ないようです。2枚目はありません。それはより簡単になることができます

var amountofclicks = 0;
var firstcard = false;
var secondcard = false;

$('#shuffle').bind('click', function() {

  var divs = $("div.choices").get().sort(function() {
    return Math.round(Math.random());
  }).slice(0, 16);

  $(divs).appendTo(divs[0].parentNode).show();

});

var firstChoise = null;

$('.choices').bind('click', function() {
  var $self = $(this);
  if (firstChoise == null) {
     firstChoise = $self.find('.letter').html();
  } else if (firstChoise == $self.find('.letter').html()) {
    alert('Choise: 2x'+firstChoise);
    firstChoise = null;
  } else {
    alert('Choise: 1x'+firstChoise+' 1x'+$self.find('.letter').html());
    firstChoise = null;
  }
});​

http://jsfiddle.net/czGZZ/1/

于 2012-12-20T15:04:51.230 に答える