javascript - 为什么 addEventListener 不调用我的 addItem 函数?

标签 javascript addeventlistener

前段时间还可以,现在不行了。控制台也没有给出任何错误。我添加了一个 console.log 字符串

console.log("You can't reach me!!");

跟踪执行流程,但是当放置在 addItem 函数中并单击 + 按钮 时字符串停止显示,这让我怀疑 addItem 函数未被调用。

事件监听器:

document.querySelector(".button").addEventListener('click', addItem);

addItem 函数:

let controller = (function(budgetCtrl, uiCtrl){

let input,newItem;

let addItem = function(){
    // 1. Get the field input data
    console.log("You can't reach me!!");
    input = uiCtrl.getInput();
    if(input.description !="" && !isNaN(input.value) && input.value > 0){

        // 2. Add the item to the budget budgetController
        newItem = budgetCtrl.addItem(input.type, input.description, input.value);
        // 3. Add the item to the UI
        uiCtrl.addListItem(newItem, input.type);

        // 4. Clear the fieldsArray
        uiCtrl.clearFields();
        // 5.Calculate and update the budget
        updateBudget();
    }


}

我在下面添加了整个代码以备不时之需。

html文件

<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Budget App</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="top">
            <div class="total">money</div>
            <div class="green">
                <span class="left">INCOME $ </span><span class="right, income-budget">+ 4,300.00</span>
            </div>
            <div class="red">
                <span class="left">EXPENSES $ </span><span class="right, expense-budget">- 1954.46</span>
            </div>
        </div>
        <div class="middle">
            <select class="operation">
                <option value="exp">-</option>
                <option selected value="inc">+</option>
            </select>
            <input class="description" type="text"  placeholder="Add description">
            <input class="value" type="number"  placeholder="value" min ="0">
            <button class="button">+</button>
        </div>
        <div class="bottom">
            <div class="bottom-left">
                <h3>INCOME</h3>
                <div class="income-list">
                    <!--
                    <div id="income-0" class="inline">
                        <div class="item-description">Salary</div>
                        <div class="item-value">+2,100.00</div>
                        <button type="button">X</button>
                    </div>
                    <!-->

                </div>
            </div>
            <div class="bottom-right">
                <h3>EXPENSES</h3>
                <div class="expense-list">
                <!--
                    <div id="expense-0" class="inline">
                        <div class="item-description">Bought car</div>
                        <div class="item-value">-2,100.00</div>
                        <button type="button">X</button>
                    </div>
                <!-->

                </div>
            </div>
        </div>
        <script src="app.js" charset="utf-8"></script>
    </body>
</html>

如果您需要整个 javascript 文件

let budgetController = (function(){
    let Expense = function(id, description, value){
        this.id = id;
        this.description = description;
        this.value = value;
    };
    let Income = function(id, description, value){
        this.id = id;
        this.description = description;
        this.value = value;
    };

    let calculateTotal = function(type){
        let sum = 0;
        data.allItems[type].forEach(function(current){
            sum += current.value;
        });
        data.totals[type] = sum;
    };

    let data = {
        allItems: {
            exp:[],
            inc:[]
        },
        totals: {
            exp: 0,
            inc:0
        },
        budget: 0
    }
    // Public method that allows other modules to add a new item to the data struc
    return{
        addItem: function(type, description, value){
            let newItem, ID;

            // Create a new ID
            if (data.allItems[type].length > 0){
                // I don't understand the .id in the following line of code
                ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
            } else{
                ID = 0;
            }

            // Create new item based on 'inc' or 'exp'
            if(type === 'exp'){
                newItem = new Expense(ID, description, value);
            }
            else if( type === 'inc'){
                newItem = new Income(ID, description, value);
            }

            // Add item to the data structure
            data.allItems[type].push(newItem);
            // Return the new element
            return newItem;
        },

        calculateBudget: function(){
                // calculate total income and expenses
                calculateTotal('exp');
                calculateTotal('inc');
                // Calculate the budget: income - EXPENSES
                data.budget = data.totals.inc - data.totals.exp;
        },

        getBudget: function(){
            return{
                budget: data.budget,
                totalInc: data.totals.inc,
                totalExp: data.totals.exp
            }
        },

        testing: function(){
            console.log(data);
        }
    };
})();

let uiController = (function(){

    return{
        getInput: function(){
            return{
                type: document.querySelector('.operation').value,
                description: document.querySelector('.description').value,
                value: parseFloat(document.querySelector('.value').value)
            };
        },
        addListItem: function(obj, type){
            let HTML, listType;
            // Create htML string with placeholder text

            if(type === 'inc'){
                element = '.income-list';
                listType = 'income';
            }else{
                element = '.expense-list';
                listType = 'expense';
            }
            HTML = '<div id="%listType%-%id%" class="inline">' +
                        '<div class="item-description">%description%</div>' +
                        '<div class="item-value">%value%</div>' +
                        '<button type="button">X</button>' +
                    '</div>'
            // Replace the placeholder text with the actual data
            HTML = HTML.replace('%listType%', listType)
            HTML = HTML.replace('%id%', obj.id);
            HTML = HTML.replace('%description%', obj.description);
            HTML = HTML.replace('%value%', obj.value);

            // Insert the htML into the DOM
            document.querySelector(element).insertAdjacentHTML('beforeend', HTML);
        },
        clearFields: function(){
            let fields, fieldsArray;
            // querySelectorAll returns a list not an array
            fields = document.querySelectorAll('.description, .value');
            fieldsArray = Array.prototype.slice.call(fields);

            fieldsArray.forEach(function(current, index, array){
                current.value ="";
            });
            // Sets focus to the descriptions field
            fieldsArray[0].focus();
        },

        displayBudget: function(object){
            document.querySelector('.total').innerHTML = object.budget;
            document.querySelector('.income-budget').innerHTML = object.totalInc;
            document.querySelector('.expense-budget').innerHTML = object.totalExp;
        }
    }

})();

let controller = (function(budgetCtrl, uiCtrl){

    let input,newItem;

    let addItem = function(){
        // 1. Get the field input data
        console.log("You can't reach me!!");
        input = uiCtrl.getInput();
        if(input.description !="" && !isNaN(input.value) && input.value > 0){

            // 2. Add the item to the budget budgetController
            newItem = budgetCtrl.addItem(input.type, input.description, input.value);
            // 3. Add the item to the UI
            uiCtrl.addListItem(newItem, input.type);

            // 4. Clear the fieldsArray
            uiCtrl.clearFields();
            // 5.Calculate and update the budget
            updateBudget();
        }


    }

    let updateBudget = function(){
        // 1. Calculate the budgetCtrl
        budgetCtrl.calculateBudget();
        // 2. Return the budget
        let budget = budgetCtrl.getBudget();
        // 3. Display the budget on the UI
        uiCtrl.displayBudget(budget);
    }

    //let ctrlDeleteItem = function(event){
    //        console.log(event.target);
    //}

    let enterKey = function(event){
        if(event.keyCode === 13 || event.which === 13){// older browers use which
        addItem();
        }
    }

    return {
        init: function(){
            const budget =  {budget: 0, totalInc:0, totalExp:0};
            uiCtrl.displayBudget(budget);
        }
    };

    document.querySelector(".button").addEventListener('click', addItem);
    document.addEventListener('keypress', enterKey);
    document.querySelector('.bottom').addEventListener('click', ctrlDeleteItem);


})(budgetController, uiController);

controller.init();

最佳答案

您的代码永远不会到达 addEventListener,因为您之前有一个 return。这是几乎无法访问的代码。

return {
    init: function(){
        const budget =  {budget: 0, totalInc:0, totalExp:0};
        uiCtrl.displayBudget(budget);
    }
};
//unreachable..
document.querySelector(".button").addEventListener('click', addItem);
document.addEventListener('keypress', enterKey);
document.querySelector('.bottom').addEventListener('click', ctrlDeleteItem);

解决方案

使用 return 切换无法访问的代码。

document.querySelector(".button").addEventListener('click', addItem);
document.addEventListener('keypress', enterKey);
document.querySelector('.bottom').addEventListener('click', ctrlDeleteItem);

return {
    init: function(){
        const budget =  {budget: 0, totalInc:0, totalExp:0};
        uiCtrl.displayBudget(budget);
    }
};

关于javascript - 为什么 addEventListener 不调用我的 addItem 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54117459/

相关文章:

javascript - `return false` 在由 addEventListener 或 element.on* 附加的事件处理程序中

javascript - 如何通过 JQuery 触发 JS native 甚至 addEventListener ("change",函数)

javascript - 为什么 chrome 控制台 jquery 甚至在我分配一个值之前就为选择选项添加了值

javascript - 未捕获的安全错误 : Failed to execute 'replaceState' on 'History' in Chrome

flash - mouseChildren = false 对我来说效果不佳

javascript - TTS HTML5 音频事件监听器

javascript - 无法删除事件监听器

javascript - 在 Vuetify v-dialog 外部单击时如何关闭它,但在 mousedown 事件而不是 mouseup 事件上执行此操作?

javascript - '如何在 vue 3 中访问设置内的数据属性?

javascript - Nivo slider v3.1