JavaScript - 在 onclick 函数中获取(this)参数的关联值

标签 javascript html onclick parameter-passing this

我通过 onclick() 将(这个)参数传递给函数。在函数中,当我尝试获取表数据单元格的调用对象的“名称”属性时,它失败了。这是代码。

<button name="abcd" onclick="foo(this)">
  Button
</button>

<table>
<tr>
  <td name="XYZ" onclick="foo(this)">Click Me Also</td>
</tr>
</table>

<script type="text/javascript">
var foo = function(xparam)
{
    // This one works for both
    alert(xparam.innerHTML);

    // This one doesn't work for Table Cell (though works for Button)
    alert(xparam.name);
};
</script>

这是 JSFiddle http://jsfiddle.net/8cvBM/312/

最佳答案

name 可能不是所有元素的属性(根据 doc table 没有 name 属性),因此请尝试 getAttribute

alert(xparam.getAttribute("name"));

关于JavaScript - 在 onclick 函数中获取(this)参数的关联值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40041500/

相关文章:

javascript - ArcGIS API - 调用函数 onClick()

javascript - 创建一个其他人可以嵌入到他们网站中的 GWT 小部件?

jquery.attr ('onclick' 在 IE7 中不起作用

javascript - 在 wicket 事件中获取变量 javascript

javascript - HTML5 Socket.IO 在 C++ 中可用吗?

html - 如何在动态 div 周围创建边框?

html - 照片在网页上以横向显示,在其他地方以垂直显示。为什么?

javascript - Angular Directive(指令)中的回调函数

javascript - jquery表单的一些问题

javascript - 如果行为空,则隐藏或删除 Google 图表中的列