jQuery 和 val() 未定义 在使用 Visual Studio 的 ASP.NET 上

jQuery and val() undefined on ASP.NET using Visual Studio

本文关键字:Studio Visual ASP NET val 未定义 jQuery      更新时间:2023-09-26

我尝试使用此代码通过jQuery获取var值。出于某种原因,名称等于 null 或未定义,我似乎无法弄清楚。

<asp:TextBox 
    ID="Text_Email" 
    runat="server" 
    CssClass="" 
    Width="234px">Email</asp:TextBox>
var name = $("#<%=Text_Email.ClientID%>").value; // name == undefined

这是我的主要脚本:

$(document).ready(function () {
    $("#<%=send_info.ClientID%>").click(function () {
        // var name = document.getElementById("#<%=Text_Name.ClientID%>").value;
        var name = $("#<%=Text_Email.ClientID%>").value;
        var reg = /^([A-Za-z0-9_'-'.])+'@([A-Za-z0-9_'-'.])+'.([A-Za-z]{2,4})$/;
         if (reg.test(name) == false) {
             $(this).val("");
             $("#error_email_adress").removeClass('email_valid');
             $("#error_email_adress").addClass('email_invalid');
             return false;
         } else {
             $("#error_email_adress").removeClass('email_invalid');
             $("#error_email_adress").addClass('email_valid');
             alert("Message sent");
             return true;
         }
     });
 });

这部分也让我感到困惑。为什么会这样?有人可以向我解释为什么在这里定义名称吗?

$("#<%=Text_Email.ClientID%>").click(function () {
    var name = this.value;//name != undefined;
});

而这里的名字是未定义的

var name = $("#<%=Text_Email.ClientID%>").value; // name == undefined;

感谢您的任何帮助。

jQuery 没有值,但 val() 函数用于文本框,

试试这个,

var name = $("#<%=Text_Email.ClientID%>").val();

您的代码将是

$("#<%=Text_Email.ClientID%>").click(function () {
       var name = $(this).val();// you will get value in name by this statement.
});

试试这个而不是你写的

$(this).val()

请注意,jquery的语法几乎很简单。关于元素值的函数是 $.val() ,您可以通过向它传递一个字符串来设置元素的值,例如:

$(this).val("the desired value");

或者,您可以通过不向元素传递任何内容来获取元素的值。

$("#<%=Text_Email.ClientID%>").click(function () {
    var name = this.value;  //<-- 'this' here is a DOM HTML Object which has .value property
    var elem = jQuery(this); //<-- converts the DOM Object into a jQuery object, jQuery does not have .value property
    var nameVal = elem.val(); //<-- get the value the jQuery way
});

阅读材料:

  • jQuery .val()