編輯我使用閉包和函數的事實很重要。像gatherData()
和voteSection()
返回顯示哪個元素被點擊的對象
我想點擊一個名爲submitButton
的div,這應該告訴我用戶做了什麼。我有3個部分。投票部分,評論部分和另一種投票部分。關鍵是現在我正在嘗試設立第一個投票部分。當我點擊submitButton
時,我應該看到一個看起來像{vote:down}
或{vote:up}
的對象。我在投票部分只有兩個按鈕。
function gatherData(){
var submitButton = ".submitButton";
var result = {}
function voteSection(){
$(".upButton").click(function(){
// result.vote = "up"
// console.log(result) ;
$(this).data("clicked", true);
$(this).siblings(".downButton").data("clicked",false)
})
$(".downButton").click(function(){
$(this).data("clicked", true);
$(this).siblings(".upButton").data("clicked",false)
// result.vote = "down";
// console.log(result) ;
})
// return result;
}
$(submitButton).on("click",function(){
if($(".upButton").data("clicked")){
result.vote = "up"
}else if($(".downButton").data("clicked")){
result.vote = "down";
}
})
return result;
}
$(".submitButton").on("click",function(){
console.log(gatherData())
})
感謝所有幫助
編輯 我才意識到自己忘了打電話給voteSection
這就是我現在有。它返回一個空對象
function gatherData(){
var submitButton = ".submitButton";
var result = {}
function voteSection(){
$(".upButton").click(function(){
// result.vote = "up"
// console.log(result) ;
$(this).data("clicked", true);
$(this).siblings(".downButton").data("clicked",false)
})
$(".downButton").click(function(){
$(this).data("clicked", true);
$(this).siblings(".upButton").data("clicked",false)
// result.vote = "down";
// console.log(result) ;
})
if($(".upButton").data("clicked")){
result.vote = "up"
}else if($(".downButton").data("clicked")){
result.vote = "down";
}
// })
return result;
// return result;
}
return voteSection()
// $(submitButton).on("click",function(){
}
$(".submitButton").on("click",function(){
console.log(gatherData())
})
點擊事件知道哪個元素被點擊,並且直接嵌入事件對象中,每個事件處理器都被傳遞。除此之外,你有問題嗎?這個網站是爲了問題,而不是一個地方轉儲你的待辦事項列表。 –
我遇到了問題,將所有內容綁在一起以在提交按鈕上返回對象。 –
你應該有一個變量,當按下投票向上或向下按鈕時得到更新。然後,您可以在需要時提交 –