如何向JavaScript函数传递参数

3
我有以下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')"/>

我该如何做到这一点?

谢谢


<input type="button" onclick="getMethod(this)"/> 这就足够了,然后你可以在 getMethod 中获取它的 id。 - Devendra Soni
5个回答

7
不要传递除了this引用和do之外的任何内容,
HTML
<input type="button" onclick="getMethod(this)"/>

JS

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

在上面的函数中,我们使用了.closest()来获取父表格,并使用.attr('id')来检索其ID。

演示


2
@RobSchmuecker parents不能比closest更有效,因为parents会查看所有的祖先,而closest在找到第一个table后就停止了-这正是此处所需的。 - RoToRa

4
<input type="button" onclick="getMethod('tbl1')"/>

更新,因为您的评论明确表明需要更加“动态”

这是一个纯JavaScript实现:

function getMethod(element) {
        // element -> td -> tr -> tbody ->table
        parentTable = element.parentNode.parentNode.parentNode.parentNode;
        alert(parentTable.id);
    }

被调用的方式:

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

Demo: http://jsfiddle.net/robschmuecker/MxWR7/1/


实际上,ID是动态生成的,而且可能有任意数量的表格。因此,我需要更自动化的东西。 - user3858417
好的 - 在这种情况下,我建议使用其中一种jQuery解决方案。 - Rob Schmuecker
@abc 你是如何生成ID的? - Grundy

2

仅传递此内容

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

在你的函数中写入以下内容:

<script>
    function getMethod(idget) {
        alert($(idget).closest("table").attr("id"));
    }
</script>

0

由于您使用了jQuery标签,因此无需编写内联代码来处理点击事件。

<table id="tbl1">
    <tr>
        <td>
            <input type="button" />
        </td>
    </tr>
</table>

jQuery代码将是:

$("#tbl1 button").click(function () {
    alert($(this).closest("table").attr("id"));
});

0
通常情况下,通过JavaScript添加事件监听器要比内联方式更好。假设您在页面上使用了jQuery:
$(document).ready(function() {
    //'#myButton' should be some jQuery identifier for your button
    $('#myButton').click(function(e) {
        getMethod('tbl1');
    });
});

然后在您的HTML中为按钮添加:

<input type="button" id="myButton">

完成了!如果你需要以编程方式标识元素的父级,请查看 [$.parents()]1


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接