gpt4 book ai didi

javascript - 如何将参数传递给javascript函数

转载 作者:搜寻专家 更新时间:2023-10-31 21:59:11 24 4
gpt4 key购买 nike

我有以下 javascript。

<script>
function getMethod(id){alert(id);}

</script>

以下是html,

<table id="tbl1">
<tr>
<td><input type="button" onclick="getMethod()"/></td>
</tr>
</table>

我需要在 html 按钮的单击事件中将表 ID“tbl1”传递给 javascript 方法 getMethod。所以我该怎么做?我想要的是这样的,(传递表 ID onclick 方法的参数)

<input type="button" onclick="getMethod('$("tbl1").ID')"/>

我该怎么做?

谢谢

最佳答案

除了 this 引用之外不要传递任何东西,

HTML

<input type="button" onclick="getMethod(this)"/>

JS

function getMethod(elem){
alert($(elem).closest('table').attr('id'));
}

在上面的函数中我们使用了.closest() 来抓取父表。并且我们使用了 .attr('id') 来检索它的 id。

DEMO

关于javascript - 如何将参数传递给javascript函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24886165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com