未捕获的TypeError:无法读取未定义的属性'querySelector'

时间:2016-04-06 09:43:02

标签: javascript jquery

你能帮助我吗?当我运行它时,我在'bindTaskEvents'函数中得到“未捕获的TypeError:无法读取未定义的属性'querySelector',其中该函数处理”completedTasksHolder“列表。在控制台中尝试这个:

console.log(completedTasksHolder.children[0]) 

返回唯一的李就好了。

var taskInput = document.getElementById("new-task"); // new-task
var addButton = document.getElementsByTagName("button")[0]; // first button
var incompleteTasksHolder = document.getElementById("incomplete-tasks"); // ul#incomplete-tasks
var completedTasksHolder = document.getElementById("completed-tasks"); // ul#completed-tasks

// Add a new task
var addTask = function(){
    console.log("Add task...");
}
// Edit an existing task
var editTask = function() {
    console.log("Edit task...");
}

var deleteTask = function() {
    console.log("Delete task...");
// Delete an existing task

    // When the Delete button is pressed
        // Remove the parent li from the ul
}

var taskCompleted = function() {
    console.log("Complete task...");
// Mark a task as complete
    // When the checkbox is checked
        // Append the task li to the #completed-tasks
}

// Mark a task as incomplete
var taskIncomplete = function() {
    console.log("Incomplete task...");
    // When the checkbox is unchecked
        // Append the task li to the #incomplete-tasks
}

var bindTaskEvents = function(taskListItem, checkBoxEventHandler) {
    console.log("Bind li events");
    // select li's children
    var checkbox = taskListItem.querySelector("input[type=checkbox]");
    var editButton = taskListItem.querySelector("button.edit");
    var deleteButton = taskListItem.querySelector("button.delete");

    // bind editTask to editButton
    editButton.onclick = editTask;

    //  bind deleteTask to deleteButton;
    deleteButton.onclick = deleteTask;

    // bind checkBoxEventHandler to checkbox
    checkbox.onchange = checkBoxEventHandler;
}

// Set the click handler to the addTask function
addButton.onclick = addTask;

// Cycle over incompleteTasksHiolder ul list items
for (var i = 0; incompleteTasksHolder.children.length; i++) {
        // bind events to li' children (taskCompleted)
    bindTaskEvents(incompleteTasksHolder.children[i], taskCompleted);
}     

// Cycle over completedTasksHiolder ul list items

for (var i = 0; completedTasksHolder.children.length; i++) {
        // bind events to li' children (taskCompleted)
    bindTaskEvents(completedTasksHolder.children[i], taskIncomplete);
}     

这里有什么不对?谢谢!

2 个答案:

答案 0 :(得分:5)

问题在于for循环

替换

for (var i = 0; incompleteTasksHolder.children.length; i++) {

for (var i = 0; i < incompleteTasksHolder.children.length; i++) {

,同样适用于completedTasksHolder

基本上你创建了一个没有结束条件的循环,在某些时候incompleteTasksHolder.children[i]undefined

答案 1 :(得分:0)

  1. &#13;
    &#13;
    var db = null;
    var db2 = null;
    var db3 = null;
    var dbUser = null;
    var dbName = "estudos.db";
    
    var app = {
        // Application Constructor
        initialize: function() {
            document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
        },
    
        // deviceready Event Handler
        //
        // Bind any cordova events here. Common events are:
        // 'pause', 'resume', etc.
        onDeviceReady: function() {
            this.receivedEvent('deviceready');
        },
    
        // Update DOM on a Received Event
        receivedEvent: function(id) {
            var parentElement = document.getElementById(id);
            var listeningElement = parentElement.querySelector('.listening');
            var receivedElement = parentElement.querySelector('.received');
    
            listeningElement.setAttribute('style', 'display:none;');
            receivedElement.setAttribute('style', 'display:block;');
    
    
            // OPERACOES BD - inicio
    
            //banco de dados local - aceite de termos e outras coisas
            dbUser = window.sqlitePlugin.openDatabase({name: 'user.db', location: 'default'});
            dbUser.transaction(function(tx) {
                tx.executeSql('CREATE TABLE IF NOT EXISTS Users (flg_aceite, flg_valid_bd)');
            }, function(error) {
                alert('Transaction ERROR: ' + error.message);
            }, function() {
                console.log('Database OK');
            });
    
            //copia do banco de dados de estudos
            window.plugins.sqlDB.copy(dbName, 0, copysuccess, copyerror);
            // OPERACOES BD - fim
        }
    };
    
    app.initialize();
    
    //---------------------------------------------------------------
    
    function copysuccess()
    {
        //primeira versão deste banco de dados. o comando anterior.
        //provavelmente realizou a cópia, abro o BD.
        db = window.sqlitePlugin.openDatabase({name: dbName});
        //preciso verificar se existem versões anteriores deste BD. Deleto por precaucao
        dropTable();
        fts_table();
    }
    
    function copyerror(e)
    {
        //esta versao do banco de dados ja existe.
        //abro o BD
        db = window.sqlitePlugin.openDatabase({name: dbName});
        //db3 = window.sqlitePlugin.openDatabase({name: "vtestudos"});
        //alert("copyerror" + JSON.stringify(e));
    }
    
    
    //---------------------------------------------------------------
    
    function fts_table(){
        db.transaction(function(tx) {
        tx.executeSql('CREATE VIRTUAL TABLE vtestudos USING FTS3(titulo, texto, id_titulo)', [], function(tx,res){
              //alert("nao deu erro");
              //db = window.sqlitePlugin.openDatabase({name: "vtestudos"});
              //alert("uai. deu pra abrir");
    
              db.transaction(function(tx) {
              tx.executeSql('INSERT INTO vtestudos(titulo, texto, id_titulo) SELECT titulo, texto, id_titulo FROM estudos', [], function(tx,res){
                  //db3 = window.sqlitePlugin.openDatabase({name: "vtestudos"});
                   console.log('insert ok');
              });
              }, function(err){
                  alert(err.message);
              });
    
        });
        }, function(err){
            alert(err.message);
        });
    }
    
    //---------------------------------------------------------------
    
    function dropTable()
    {
        window.plugins.sqlDB.remove("estudosprev1", 0, rmsuccess,rmerror); 
        window.plugins.sqlDB.remove("estudosprev2", 0, rmsuccess,rmerror);  
    }
    
    function rmsuccess()
    {
        //existe versão anterior
        //alert("removesuccess");
        console.log('existe versão anterior');
    }
    
    function rmerror(e)
    {
        //não existe versão anterior. ignoro.
        //alert("removeerror" + JSON.stringify(e));
        console.log('n existe versão anterior. ignoro.');
    }
    &#13;
    &#13;
    &#13;