所以我想做一個簡單的待辦事項列表,其中我有我創建的每個列表項的複選框。每次我更改與特定任務相關的複選框時,我都想調用一個具有if else語句的函數。 if else語句會告訴我,如果該框被選中或未選中,並根據該邏輯進行編碼。問題是,我不知道如何訪問我指的特定複選框,因爲每個任務都是通過javascript創建的,並且沒有唯一的ID。onchange屬性:從此調用函數時的上下文究竟是什麼?
所以他這樣說我的問題是:
如何我指的是具體的複選框我改變?我是否使用「this」關鍵字?如果是的話,那麼在這種特殊情況下,「這個」究竟是指什麼呢?
這裏是我的js代碼:
$("#add").button();
$("#remove").button();
//Constructor for ToDo Object
function ToDo(name){
this.name = name;
}
ToDo.prototype.addItem = function(string){
var list = document.querySelector("#list");
var listItem = document.createElement("div");
var listItemPar = document.createElement("p");
var listItemText = document.createTextNode(string);
var checkBox = document.createElement("input")
checkBox.setAttribute('type','checkbox');
checkBox.className = "checkBoxes"
checkBox.setAttribute("onchange","checkedBoxes()")
var removeButton = document.createElement("button")
removeButton.className = "removeButtons"
list.appendChild(listItem);
listItem.appendChild(listItemPar);
listItemPar.appendChild(listItemText);
listItem.appendChild(checkBox);
listItem.appendChild(removeButton);
$("button.removeButtons").button();
$(".removeButtons").hide();
document.querySelector("#input").value = "";
};
ToDo.prototype.removeItem = function(){
console.log("remove item");
}
document.querySelector("#remove").addEventListener("click",function(){
item = new ToDo();
item.removeItem();
window.alert("hi");
})
document.querySelector("#add").addEventListener("click",function(){
var item = new ToDo();
item.addItem(document.querySelector("input").value);
})
function checkedBoxes(){
//function I am referring to
}
所以在代碼中,我指的是checkBox.setAttribute( 「平變化」, 「checkedBoxes()」),該函數是在底部。 HTML實際上並不是特別重要,因爲我通過JavaScript創建了幾乎所有的東西,但是如果您需要查看它以幫助我知道。
在此先感謝
驚人的細節,謝謝你幫助我瞭解情況! – Javascripter