0

我有一个 div 列表,我想要实现的是当用户单击 column 时,它会获取数据方将其分配给变量 from,当再次单击另一列时,它将数据分配给变量。

我确实知道如何通过 ajax 向 php 发送值,只是从和到获取变量的事实是问题所在。这是一个棋盘游戏,我需要将两个变量从和到发送到服务器

<div class="column" data-square="4-4">
    <div class="lol">p</div>
</div>
<div class="column" data-square="4-5">
    <div class="lol">p</div>
</div>

<div class="column" data-square="4-6">
    <div class="lol">p</div>
</div>

$( ".column" ).click(function(){
    var from = $(this).data('square');
    var to = $(this).data('square');    
    alert(to);
    alert(from);
});

假设有 10 个 div //其中 10 个具有不同的 data-square p 值,其中用户点击其中一个,它应该将数据平方值存储在变量中,当用户再次点击另一个 div 时,它应该存储变量在变量中

4

3 回答 3

2

这是一种方法。使变量可以从点击事件外部访问fromto跟踪它们的值。首先为 赋值from,然后为to并执行您的 ajax 请求。Javascript 看起来像这样:

// Create a function scope so we don't messy the global one
(function() {

    var from = null;
    var to = null;

    $(".column" ).click(function(){
        if(from === null)
        {
            from = $(this).data('square');
        }
        else
        {
            to = $(this).data('square');

            //
            // DO YOUR AJAX STUFF HERE
            //

            // Reset
            from = to = null;
        }
    });

}());

这是一个 JSFiddle 演示

于 2012-04-22T14:01:37.753 回答
0

摆弄:

http://jsfiddle.net/iambriansreed/4674X/ HTML:

<div id="notes">
    <span class="note1">Click Move From</span>
    <span class="note2">Click Move To</span>
    <span class="note3"></span>
</div>
<div class="column" data-square="4-4">
    <div class="lol">p</div>
</div>
<div class="column" data-square="4-5">
    <div class="lol">p</div>
</div>

<div class="column" data-square="4-6">
    <div class="lol">p</div>
</div>

jQuery: var from_data = false, to_data = false;

$('#notes .note1').show().siblings().hide(); 

$( ".column" ).click(function(){

    if(from_data && to_data) return;  

    if(!from_data){
        $('#notes .note2').show().siblings().hide(); 
        from_data = $(this).data('square');

    }else if(!to_data){
        to_data = $(this).data('square');

        $('#notes .note3').text(
        'Moved from '+from_data+' to '+to_data+'.'
        ).show().siblings().hide();


        setTimeout(function(){
            $('#notes .note3').fadeOut(function(){
                from_data = false; to_data = false;
                $('#notes .note1').show().siblings().hide();                
            });        
        },2000);

    }

});​
于 2012-04-22T14:13:47.127 回答
0

如果您知道 Jquery ajax 关系,您应该使用 Jquery 的 ajax 函数 ( $.ajax({... });) 将数据传递到您的 php 文件,并使用 JSON 类型。echo json_encode($array);您可以在 php 的 json_encode 函数(如)之后从 php 文件中获取一个数组。

于 2012-04-22T14:08:04.160 回答