简体   繁体   English

从 JavaScript function 返回行索引,返回未定义

[英]Returning Row Index from JavaScript function ,returns undefined

    function getRowIndex() {
    var tble = document.getElementById("myTable");
    for (var i = 0; i < tble.rows.length; i++) {
        for (var j = 0; j < tble.rows[i].cells.length; j++) {
            tble.rows[i].cells[j].onclick = function() {

                return this.parentElement.rowIndex;
            }
        }
    }
}
var rIndex = getRowIndex();
console.log(rIndex);

This function getRowIndex() is returning undefined when I try to print index.当我尝试打印索引时,此 function getRowIndex()返回未定义。 I want to extract the row index value in value when clicked, using javaScript .我想在单击时提取行索引值,使用javaScript

I am assuming that you are using HTML table element.我假设您正在使用 HTML table元素。 You can find row index like this:您可以像这样找到行索引:

 document.getElementById('myTable').addEventListener('click', (e) => { if (e.target.nodeName === 'TD') { alert(e.target.parentNode.rowIndex); } });
 table { border-collapse: collapse; } td { border: 1px solid; padding: 10px; cursor: pointer; }
 <table id="myTable"> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>4</td> <td>5</td> <td>6</td> </tr> </table>

I am using event delegation here.我在这里使用event delegation Instead of iterating over each child element and then bind the event.而不是遍历每个子元素然后绑定事件。 I am binding the event to parent node itself and then find the click target using event.target .我将事件绑定到父节点本身,然后使用event.target找到点击目标。 This has great performance benefits as you can already see.正如您已经看到的那样,这具有很大的性能优势。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM