我有一個id'ed td元素的表格(跳棋遊戲板)。我想建立一些jQuery代碼,做這樣的事情用JQuery發佈混合JQuery點擊事件
獲得一個點擊TD元素的ID,將其設置爲「從」,如果它是空的
獲得一個點擊TD的ID元件,將其設置爲「到」如果「從」填充
張貼「從」和「到」 IDS到服務器,與板對象表示板狀態
我已經完成了一些教程,但是我一直無法將它們拼湊在一起。
我有一個id'ed td元素的表格(跳棋遊戲板)。我想建立一些jQuery代碼,做這樣的事情用JQuery發佈混合JQuery點擊事件
獲得一個點擊TD元素的ID,將其設置爲「從」,如果它是空的
獲得一個點擊TD的ID元件,將其設置爲「到」如果「從」填充
張貼「從」和「到」 IDS到服務器,與板對象表示板狀態
我已經完成了一些教程,但是我一直無法將它們拼湊在一起。
對於1 & 2您將希望使用jQuery選擇器來選擇表中的所有td元素。然後,您可以使用click方法將相同的點擊處理程序應用於所有人。例如。
$('#tableId').children('td').click(handler);
'處理程序'應該是一個你已經聲明的函數,
var from;
function handler(){
if (from){
$.post('url', { from : from, to : this.id });
from = null;
} else {
from = this.id;
}
}
我不知道這是否是你想要的到底是什麼,但是這是我從你的描述可以理解:
var from = "";
var to = "";
$("td").click(function(){ // fires when you click on a td element. You could also use $(".some_class") for example
if(from=="") { // if "from" is still empty
from = $(this).attr('id'); // define as id of this element
} else if(from!="") { // if "from" is already filled
to = $(this).attr('id');
$.post("/file.php", { firstvar: from, secondvar: to }); // posts variables "from" and "to" as "firstvar" and "secondvar"
from = ""; // reset the variables
to = "";
}
});
當數據應該得到postet你沒有說,所以我寫的在別人,因爲我認爲你要發佈它的話..
在file.php你可以得到的數據作爲$_POST["firstvar"]
和$_POST["secondvar"]
$.ajax({
type: 'POST',
url: '/file.php',
data: { firstvar: from, secondvar: to },
cache: false,
success: function(data) {
// the output of this file was saved in "data"
// something you want to do on success
},
error: function(xhr, ajaxOptions, thrownError){
alert('there was an error');
}
});
這將開展
你需要寫你getBoardState()
功能,這可能是這樣的
function getBoardState() {
var state = {};
$("#board").find("td").each(function() {
var $this = $(this);
state[$this.attr("id")] = $this.hasClass("occupied");
});
return state;
}
此外,你需要小心的基礎性工作
var from, to;
$("#board").on("click", "td", function() { // or, if using earlier than v1.7 jquery $("#board").delegate("td", "click", function()
if (!from) {
from = $(this).attr("id");
} else {
to = $(this).attr("id");
$.post("/file.php", {
from: from,
to: to,
state : getBoardState()
});
from = to = null;
}
});
關於在等待帖子從服務器回來時禁用/處理點擊次數
個的絕對基礎是相當容易的放在一起,這增加了必須選擇「從」第一,檢查孩子們演示多一點的邏輯:用於獲取的ID,而無需創建一個新的jQuery實例http://jsfiddle.net/VW94F/
var $brd = $('#board').click(function(evt) {
var $cell = $(evt.target).closest('td');
if ($cell.children().length) {
$('.from').removeClass('from');
$cell.addClass('from');
$brd.data('from', $cell[0].id);
} else {
if (!$('.from').length) {
alert('Select "from" first');
return;
}
$cell.addClass('.to');
var to=$cell[0].id, from= $brd.data('from');
$brd.data('to', to);
$.post(url, {from: from,to: to},function(data) {
// do something on ajax success
$brd.removeData()
});
alert('From: ' + from + '\n To:' + to)
}
})
+1。 ..好習慣 – wheresrhys 2012-02-27 16:19:20
+1絕對同意 – Fabian 2012-02-27 16:31:13
有沒有寫'$(this).attr('id')'好些?當我需要它時,我傾向於使用jQuery作爲工具,並且我不明白爲什麼你會在這種情況下創建一個新的jQuery實例? – OlduwanSteve 2012-02-27 16:37:59