如何将EventListener添加到表单元格 [英] How to addEventListener to table cells

查看:66
本文介绍了如何将EventListener添加到表单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向表单元格添加一个eventListener,以便每次单击表单元格来执行一个函数.

I'want to add an eventListener to the table cells so each time a table cell is clicked to execute a function .

var getDaysInMonth = function (year, month) {
    return new Date(year, month, 0).getDate();
}



var calendar = {
    month: function () {
        var d = new Date();
        return d.getMonth() + this.nextMonth;
    },

    year: function () {
        var y = new Date();
        return y.getFullYear();
    },

    nextMonth: 1,
    
    cellColor: 'white',
    
}



var loopTable = function () {
    var daysInMonth = getDaysInMonth(calendar.year(), calendar.month());
    var table = document.getElementById('myTable');
    var rows = table.rows;
    var l = 1;
    var month = calendar.month();
    var year = calendar.year();
    var firstDay = new Date(year + "-" + month).getDay();
    var currentDay = new Date().getDay();
    var dayOfMonth = new Date().getDate();

 
    for (let i = 1; i < rows.length; i++) {

        if (rows[i] == rows[1]) {

            var k = 1;

            for (let j = firstDay; j < rows[i].cells.length; j++) {

                if (k === dayOfMonth && calendar.nextMonth === 1) {
                    rows[i].cells[j].style.backgroundColor = calendar.cellColor;
                

                }

                if (k <= daysInMonth) {
                    rows[i].cells[j].innerHTML = k;
                    k++
                }

            }
        } else {
            for (let j = 0; j < rows[i].cells.length; j++) {
                if (k === dayOfMonth && calendar.nextMonth === 1) {
                    rows[i].cells[j].style.backgroundColor = calendar.cellColor;
                }
                if (k <= daysInMonth) {
                    rows[i].cells[j].innerHTML = k;
                    k++
                }
            }
        }
    }
}

loopTable();
clickCell();

function monthTitle() {

    var monthsArray = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.', 'Sept.', 'Oct.', 'Nov.', 'Dec.'];
    monthNum = calendar.month();
    var monthName = monthsArray[calendar.month() - 1] + '' + calendar.year();
    var title = document.getElementById('calendarTitle');
    var nextArrow = document.getElementById('nxt');
    var leftArrow = document.getElementById('prev');

  
    if (monthName === ('Dec.' + '' + calendar.year())){
        xmas();
    }
    if (monthNum >= 12) {
        nextArrow.className += ' inactiveLink';
    } else if (monthNum <= 1) {
        leftArrow.className += ' inactiveLink';
    } else {
        nextArrow.classList.remove('inactiveLink');
        leftArrow.classList.remove('inactiveLink');
    }

    title.innerHTML = '';
    var titleNode = document.createTextNode(monthName);
    title.appendChild(titleNode);


}
monthTitle();

function nextMonth() {
    clearTable();
    calendar.nextMonth += 1;
    monthTitle();
    loopTable();
}

function previousMonth() {
    clearTable();
    calendar.nextMonth -= 1;
    monthTitle();
    loopTable();
}

function clearTable() {
    var table = document.getElementById('myTable');
    var rows = table.rows;

    for (var i = 1; i < rows.length; i++) {
        cells = rows[i].cells;
        for (var j = 0; j < cells.length; j++) {
            if (cells[j].innerHTML = '') {
                cells[j].style.display = 'none';
            }
            cells[j].innerHTML = '';
            cells[j].style.backgroundColor = '#D9534F';
            cells[j].style.emptyCells = 'hide';
        }
    }
}

var next = document.getElementById('nxt');
var previous = document.getElementById('prev');
var table = document.getElementById('myTable');
var cell = table.rows;
next.addEventListener('click', nextMonth);
previous.addEventListener('click', previousMonth);



function clickCell() {
    var row = document.getElementById('myTable').rows;
    
    for (var i = 0; i < row.length; i++) {
        for (var j = 0; j < row[i].cells.length; j++ ) {
  					
            row[i].cells[j].addEventListener('click', function(){
  					console.log('click');
            })
        }
    }
}
clickCell();

body {
            background-color: rgb(0, 121, 191);
        }
        
        table {
            width: 50%;
            background-color: #D9534F;
            border: 1px solid white;
            padding: 10px;
            padding-bottom: 20px;
            font-size: 25px;
            border-radius: 25px;
            position: relative;
            margin: auto;
        }
        
        td {
            border: 1px solid white;
            text-align: center;
            font-weight: 600;
            font-size: 20px;
            padding: 20px;
        }
        
        th {
            height: 50px;
        }
        
        .calArrows {
            text-decoration: none;
            color: white;
            font-size: 35px;
        }
        
        #nxt {
            font-size: 30px;
            position: absolute;
            top: 0;
            right: 25%
        }
        
        #prev {
            font-size: 30px;
            position: absolute;
            top: 0;
            left: 25%;
        }
        
        #calendarTitle {
            font-family: 'Indie Flower', cursive;
            font-weight: 600;
            font-size: 25px;
            color: white;
        }
        
        .inactiveLink {
            cursor: not-allowed;
            pointer-events: none;
             
        }
        
        #myTable {
            empty-cells: hide;
        }
        
        .xmasDec {
            width: 90%;
            height: 70%;
            position: absolute;
            top: -10%;
            left: 5%;
        }
        
        #calWraper {
            position: relative;
        }
        
        #myCan {
            position: absolute;
            top: 0;
            left: 10%;
            width: 90%;
            height: 70%;
            opacity: 0, 5;
        }

<body>
    <canvas class="myCan" width="100" height="100"></canvas>
    <div id="calWraper">
        <table id="myTable">
            <caption id="calendarTitle">Test</caption>
            <tr>
                <th>Sun</th>
                <th>Mon</th>
                <th>Tue</th>
                <th>Wed</th>
                <th>Thur</th>
                <th>Fri</th>
                <th>Sat</th>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td></td>
            </tr>
        </table>
        <canvas id="myCan" width="200" height="200" style="background-color: transparent"></canvas>
            <a href="#" id="prev" class="calArrows"><i class="fa fa-arrow-left" ></i></a>
        <a href="#" id="nxt" class="calArrows"><i class="fa fa-arrow-right" ></i></a>



    </div>



</html>

我尝试创建一个函数,该函数将遍历行和单元格并将eventListener添加到每个函数中.但是似乎它不起作用,它在随机实例上起作用,这确实是奇怪的行为.这是我创建的功能:

I tried by creating a function that it will loop through rows and cells and add the eventListener to each . But it seems that its not working , its working on random instances which is really strange behavior . Here is the function i create:

function clickCell() {
    var row = document.getElementById('myTable').rows;
 for (var i = 0; i < row.length; i++) {
        for (var j = 0; j < row[i].cells.length; j++ ) {
                    console.log(row[i].cells[j].innerHTML);
            row[i].cells[j].addEventListener('click', function(){
                    console.log('click');
            })
        }
    }
}

推荐答案

似乎您的画布在桌子上重叠了.因此,永远不会点击表中的 td 元素.

It seems your canvas is overlapping your table. Because of that td elements in your table are never clicked.

您将需要在画布上添加CSS属性 pointer-events:none .

You will need to add CSS property pointer-events:none to your canvas.

#myCan {
    ...
   pointer-events: none;
}

这样,它就不会再阻止单击表了.

This way it won't block table from being clicked anymore.

您还可以将事件侦听器添加到您的单元格中,方法更简单:

You can also add event listeners to your cells way simpler:

document.querySelectorAll('#myTable td')
.forEach(e => e.addEventListener("click", function() {
    // Here, `this` refers to the element the event was hooked on
    console.log("clicked")
}));

为每个单元格创建一个单独的函数;相反,您可以共享一个功能而不会失去任何功能:

That creates a separate function for each cell; instead, you could share one function without losing any functionality:

function clickHandler() {
    // Here, `this` refers to the element the event was hooked on
    console.log("clicked")
}
document.querySelectorAll('#myTable td')
.forEach(e => e.addEventListener("click", clickHandler));


某些浏览器在 querySelectorAll 返回的HTMLCollection上仍然没有 forEach ,但是可以很容易地对其进行填充:


Some browsers still don't have forEach on the HTMLCollection returned by querySelectorAll, but it's easily polyfilled:

if (!HTMLCollection.prototype.forEach) {
    Object.defineProperty(HTMLCollection.prototype, "forEach", {
        value: Array.prototype.forEach
    });
}

如果您必须支持没有 Array.prototype.forEach 的真正过时的浏览器,请参见

If you have to support truly obsolete browsers that don't have Array.prototype.forEach, see the polyfill on MDN.

这篇关于如何将EventListener添加到表单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆