【问题标题】:JavaScript - Fetching Associated Values of (this) Parameter in an onclick FunctionJavaScript - 在 onclick 函数中获取 (this) 参数的关联值
【发布时间】:2017-02-23 18:54:18
【问题描述】:

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

<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/

【问题讨论】:

    标签: javascript html onclick parameter-passing this


    【解决方案1】:

    name 可能不是所有元素的属性(根据doc table 没有名称属性),所以试试getAttribute

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

    【讨论】:

      猜你喜欢
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      相关资源
      最近更新 更多