>我有一个div列表,我想要实现的是当用户单击列时,它获取数据方块将其分配给变量,当再次单击另一列时,它将数据分配给变量。
我确实知道如何通过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 个具有不同数据平方值的 p 当用户单击其中一个时,它应该将数据平方值存储在变量中,当用户再次单击另一个div时,它应该将数据平方值存储在变量中
这是一种方法。使变量from
,to
可从点击事件外部访问,并跟踪其值。首先给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 演示
如果你知道Jquery ajax关系,你应该使用Jquery的ajax函数($.ajax({... });
)和JSON类型将数据传递给你的php文件。你可以在php的json_encode函数(如echo json_encode($array);
)之后从php文件中获取一个数组。
摆弄:
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>
j查询: var from_data = 假,to_data = 假;
$('#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);
}
});