简体   繁体   English

如何在 Table JavaScript 中获取选定的表格单元格?

[英]How to get selected table cell in in Table JavaScript?

How to get selected table cell in in Table JavaScript without using jQuery?如何在不使用 jQuery 的情况下在 Table JavaScript 中获取选定的表格单元格? With jQuery decision is very simple, but in JavaScript without jQuery - I don't know how.使用 jQuery 决定非常简单,但在没有 jQuery 的 JavaScript 中——我不知道如何。 I have table:我有表:

<table><tr onmouseover="toolnote(this)"><td><td><td></tr></table>

I need to bind "onmouseover" event to every cell in table, but if write this event to every cell it will be very unreadable.我需要将“onmouseover”事件绑定到表中的每个单元格,但如果将此事件写入每个单元格,它将变得非常不可读。 It follows that I must bind "onmouseover" to tag through the child and there determine the selected cell.因此,我必须将“onmouseover”绑定到通过子项进行标记并确定所选单元格。 But I do't lnow how get the child index.但我不知道如何获得子索引。

JS Code: JS代码:

function toolnote(el){
    var tt = el.getElementsByTagName('td')
    alert(tt[0].innerHTML);
}

In this sample event binding to 0-index.在此示例事件绑定到 0-index。

Anybody help me?有人帮帮我吗?

Doubt!怀疑!

  1. You have toolnote() as the function name and you are calling tooltip() on the element.您将toolnote()作为函数名称,并在元素上调用tooltip() Is this a typo?这是一个错字吗?
  2. You are missing a ;你错过了一个; in the statement.在声明中。

Simple Change:简单的改变:

function toolnote(el){
    var tt = el.getElementsByTagName('td'); // «--- You are missing a ;
    alert(tt[0].innerText);
}

Or, if you use jQuery , then it is still easier.或者,如果您使用jQuery ,那么它仍然更容易。

function toolnote(el){
    alert($(el).children("td").first().text());
}

You need this in each cell, then:您需要在每个单元格中使用它,然后:

<tr><td onmouseover="toolnote(this)"></td><td onmouseover="toolnote(this)"></td><td onmouseover="toolnote(this)"></td></tr>

Make the JavaScript this way:以这种方式制作 JavaScript:

function toolnote(el){
    alert(this.innerText);
}

In case of Firefox :如果是Firefox

function toolnote(el){
    alert(this.textContent);
}

And this is the reason, I said it will be better to use jQuery , as it handles this cross browser scripting issue, in a better way.这就是原因,我说使用jQuery会更好,因为它可以更好地处理跨浏览器脚本问题。


In a Single Line:在一行中:

function toolnote(el) {
    var e = el.getElementsByTagName("td");
    if (e.textContent)
        for (i = 0; i < e.length; i++) e[i].onclick = function () {
            alert(this.textContent); // Firefox
        }
    else
        for (i = 0; i < e.length; i++) e[i].onclick = function () {
            alert(this.innerText); // IE
        }
}

in the tr call onload="setUpToolnote(this);"在 tr 中调用 onload="setUpToolnote(this);"

function toolnote(){
     alert(this.innerText);
}
function setUpToolnote(el){
 var tt=el.getElementsByTagName('td'); 
for(var i=0;i<tt.length;i++){
tt[i].addEventListener("mouseover", toolnote);
}
}

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

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