在 Javascript 中获取 ClientID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8152049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:28:25  来源:igfitidea点击:

Get ClientID in Javascript

javascriptjqueryasp.net

提问by Arian

I have a javascript file that Select a button using jQuery and check it for validation.the code is:

我有一个 javascript 文件,它使用 jQuery 选择一个按钮并检查它的验证。代码是:

$(document).ready(function () {
$('#<%= btn_Insert.ClientID %>').on("click", function (event) {

    if (Validate() != true) {
        event.preventDefault();
    }
});
function Validate() {
    return (1 == 1);
});

but I can' get ClientIDfor button and I get this Error:

但我无法获取ClientID按钮并收到此错误:

Object doesn't support this property or method

对象不支持此属性或方法

where is my mistake?How I can get Client ID for a server side Button?

我的错误在哪里?如何获取服务器端按钮的客户端 ID?

thanks

谢谢

EDIT 1)

编辑 1)

When I add script in headpart of page it works but when I write it to a JS file and add reference to it in headpart it does not work

当我在head页面的一部分中添加脚本时它可以工作但是当我将它写入一个 JS 文件并部分添加对它的引用时它head不起作用

回答by Darin Dimitrov

I suspect that the error comes from the fact that eventhas a special meaning in some browsers. Try renaming the variable:

我怀疑该错误来自event在某些浏览器中具有特殊含义的事实。尝试重命名变量:

function Validate() {
    return (1 === 1);
}

$(function () {
    $('#<%= btn_Insert.ClientID %>').on('click', function (evt) {
        if (!Validate()) {
            evt.preventDefault();
        }
    });
});

or even easier :

甚至更容易:

$('#<%= btn_Insert.ClientID %>').on('click', function() {
    return Validate();
});


UPDATE:

更新:

Now that you have edited your question it is clear where the problem is. You are trying to use server side tags (<%= %>) in a separate javascript file. That's impossible. They will render literally and will not be processed by ASP.NET.

现在您已经编辑了您的问题,很明显问题出在哪里。您正尝试<%= %>在单独的 javascript 文件中使用服务器端标记 ( )。这不可能。它们将按字面呈现,不会由 ASP.NET 处理。

In order to solve your issue you could apply a CSS class to the button and then use a class selector:

为了解决您的问题,您可以将 CSS 类应用于按钮,然后使用类选择器:

$('.someClass').on('click', function() {
    ...
});

Another possibility is to use the ends with selector:

另一种可能性是使用带有选择器结尾

$('[id$="btn_Insert"]').on('click', function() {
    ...
});

回答by jo_asakura

Just add ClientIDMode="Static"to your server button control and use its ID in js w/o problems:

只需添加ClientIDMode="Static"到您的服务器按钮控件并在没有问题的 js 中使用其 ID:

$('btn_Insert').on('click', function() {
    return Validate();
});