为什么 Jquery 不适用于文本框 asp.net CssClass 属性

本文关键字:asp net CssClass 属性 文本 Jquery 不适用 适用于 为什么 | 更新日期: 2023-09-27 18:35:20

我正在使用 Jquery 验证文本框以在页面中实现 asp.net"仅字母表"属性。

这是代码

    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
     .............codes.............
      <script type="text/javascript">
    $('.alph').keypress(function (e) {
        var regex = new RegExp("^[a-zA-Z's]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else {
            e.preventDefault();
            alert('Alphabets only');
            return false;
        }
    });
   </script>
 .............codes.............
 <asp:TextBox ID="txt_name" CssClass="alph" BorderColor="Gray" Font-Size="Large" Height="25" Width="250" runat="server"></asp:TextBox>

此代码不起作用,我确定我的计算机已连接到互联网以访问 code.jquery.com。请帮帮我。

为什么 Jquery 不适用于文本框 asp.net CssClass 属性

Document.ready块后尝试此脚本代码

$(document).ready(function(){
    $('.alph').keypress(function (e) {
        var regex = new RegExp("^[a-zA-Z's]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else {
            e.preventDefault();
            alert('Alphabets only');
            return false;
        }
    });
});

在安全地使用 jQuery 之前,您需要确保页面处于准备好作的状态。使用 jQuery,我们通过将代码放在一个函数中,然后将该函数传递给 $(document).ready() 来实现这一点。我们传递的函数可以只是一个匿名函数。

我的错误!由于我是 Jquery 的新手,我不知道"doc.ready",我更正了代码

$(document).ready(function () {
 $('#<%=txt_name.ClientID %>').keypress(function (e) {
        var regex = new RegExp("^[a-zA-Z's]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else {
            e.preventDefault();
            alert('Alphabets only');
            return false;
        }
    });
    });

代码完美运行!