首页 > 解决方案 > 当'this'作为参数从外部js文件传递给函数时如何访问控件的ID

问题描述

我有一个 asp 按钮,当它被点击时,它会从外部 javascript 文件中调用一个函数。关键字作为this参数传递。这样做的目的是让函数检索控件的 id。该功能将被其他按钮重用。

问题是,在传递时,传递this的对象将包含ClientID外部js函数没有想法的对象。

我不想像OnClientClick="toggle('btnClick')". 我的按钮控件如下所示:

<asp:Button ID="btnClick" runat="server" OnClientClick="toggle(this); return false;"/>

我的外部 js 函数如下所示:

function toggle(button){
console.log(button);//currently, the id shown in console
                    //is the ClientID. I just want to get the "btnClick" ID
//do something about the button after retrieving the ID
}

标签: javascriptasp.net

解决方案


现在 web.config 中有一个设置可以解决 ClientID 问题。这将呈现 ID 在标记中的样子。

<system.web>
    <pages clientIDMode="Static">
</system.web>

并确保您要求button.id.


推荐阅读