简体   繁体   English

如何为单个表格单元格制作事件侦听器(onclick)

[英]How do I make an event Listener (onclick) for a single Table Cell

my question is: How can I make a table cell, for example, change text on click?我的问题是:如何制作表格单元格,例如,单击时更改文本? I tried this:我试过这个:

 function randomFunction() { document.getElementById("randomId").innerText = "random text" }
 <table> <tr> <td id="randomId" onclick="randomFunction()">random text</td> </tr> </table>

but it does the onclick attribute for the entire row.但它对整行执行 onclick 属性。

Is it possible to trigger the function only when I click on the cell ?是否可以仅在单击单元格时触发该功能?

Yes it possible.是的,有可能。 you have pass the context to the function.您已将上下文传递给函数。 I put more cells in your table.我在你的桌子上放了更多的单元格。

 function randomFunction(e){ e.innerText = "HuhU" // document.getElementById("randomId").innerText = "random text!" }
 td { background: green; color:white; }
 <table> <tr> <td id="randomId" onclick="randomFunction(this)">random text</td> <td id="randomId" onclick="randomFunction(this)">random text</td> <td id="randomId" onclick="randomFunction(this)">random text</td> </tr> </table>

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

相关问题 如何将 onClick 事件侦听器添加到表中? - How can I add an onClick event listener to a table? 如何为表格单元格的内部 html 创建 OnClick 事件 - How do I create an OnClick Event for a table cell's inner html 表格单元事件监听器 - Table cell event listener 如何使用单个事件监听器而不是每个按钮中的 onclick 事件来做一个迷你计算器? - How to do a mini calculator using a single event Listener instead of onclick events in each button? 如何将事件侦听器添加到表中的每个单元格? - How to add event listener to each cell in a table? 我如何为 forwach 循环中的按钮创建事件侦听器 - how do i make a event listener for a button that is in a forwach loop 就像我们在html的onclick事件监听器中一样,如何在Javascript的onClick事件监听器中传递字符串值 - How to pass string value in onClick event listener in Javascript as we do it in onclick event listener in html 如何为表格中的自定义选择做事件监听器? - How can i do event listener for a custom select in the table? 如何为动态添加的复选框创建 onclick 事件? (JavaScript) - How do I make an onclick event for a dynamically added checkbox? (JavaScript) 如何使onclick事件跳到offclick? - How do I make onclick event skip to offclick?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM