简体   繁体   English

ASP.Net中的电话掩码

[英]Phone Mask in ASP.Net

i am doing a ASP.Net application and I need to use phone mask input in a TextBox. 我正在做一个ASP.Net应用程序,我需要在TextBox中使用电话掩码输入。 I am using jQuery and it is not working. 我正在使用jQuery,但无法正常工作。

Asp.net: Asp.net:

<asp:TextBox runat="server" ID="txtCelular" CssClass="w240 placeholder"></asp:TextBox>

javascript: javascript:

    <script src="\scripts\jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
    $("#txtCelular").mask("(999) 9999-9999?9");


    $("#txtCelular").on("blur", function () {
        var last = $(this).val().substr($(this).val().indexOf("-") + 1);

        if (last.length == 5) {
            var move = $(this).val().substr($(this).val().indexOf("-") + 1, 1);

            var lastfour = last.substr(1, 4);

            var first = $(this).val().substr(0, 9);

            $(this).val(first + move + '-' + lastfour);
        }
    });
</script>

You have to keep in mind that the ID you specify on elements on the server, by default, is not the ID that is used on the client. 您必须记住,默认情况下,您在服务器上的元素上指定的ID不是客户端上使用的ID。 And since JavaScript runs on the client, then it's not getting the right element because of the ID mismatch. 而且由于JavaScript在客户端上运行,所以由于ID不匹配,所以没有得到正确的元素。 You have a number of options. 您有很多选择。 This often trips up new Web Forms developers when they start using Master Pages, templated controls, or user controls (.ascx). 当新的Web Forms开发人员开始使用母版页,模板化控件或用户控件(.ascx)时,这通常会使他们苦恼。


Change Client Id Mode approach 更改客户ID模式方法

You can change ClientIdMode for the element (this can also be done at the page or web.config levels). 您可以更改元素的ClientIdMode(也可以在页面或web.config级别上完成)。

<asp:TextBox runat="server" ID="txtCelular" ClientIdMode="static" CssClass="w240 placeholder" />

Embed Client ID approach 嵌入客户ID方法

You can embed the Client ID in the JavaScript, as long as your JavaScript is directly in a Web Forms page or control. 只要您的JavaScript直接在Web窗体页面或控件中,就可以将Client ID嵌入到JavaScript中。

$("#<%= txtCelular.ClientId %>").mask("(999) 9999-9999?9");

Use a class approach 使用课堂方法

Or in some situations (this is a good candidate), a class makes more sense. 或者在某些情况下(这是一个很好的候选人),一堂课更有意义。

<asp:TextBox runat="server" ID="txtCelular" CssClass="w240 placeholder phonemask" />

$(".phonemask").mask("(999) 9999-9999?9");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM