jQuery 对象.value returns 未定义

jQuery object .value returns undefined

我正在构建一个简单的聊天,但卡在了前端。

我想在加载聊天之前询问用户的姓名和想要的房间 window,我需要一些变量中的数据。问题是浏览器只记录 undefined。我也尝试直接从代码和 Chrome 控制台登录。

var nameChoice, roomChoice;

var init = function() {

    $("#init-name").removeClass("hidden").animate({"left" : "35%"}, 300); //slide in name form

    $("#init-name .btn-form").click(function() {

        nameChoice = $("#init-name input").value; //save chosen name in nameChoice?
        console.log(nameChoice); //debug
        $("#init-name").animate(
            {"left" : "-35%"}, 300,
            function() {
                $(this).addClass("hidden");
                $("#init-room").removeClass("hidden");
                $("#init-room").animate({"left" : "35%"}, 300);
        });  //remove name form and slide in room form in callback
    });
    $("#init-room .btn-form").click(function() {
        roomChoice = $("#init-room select").value; //save chosen room in roomChoice?
        console.log(roomChoice); //debug
        $("#init-room").animate(
            {"left" : "-35%"}, 300,
            function() {
                $(this).addClass("hidden");
                $("#chat-main").removeClass("hidden");
        }); //remove room form and show page in callback
    });
}
$(document).ready(init);

它是否必须对可变范围做任何事情(我确实将它们放在任何函数之外)?

您需要使用 val 函数才能获取值。

http://api.jquery.com/val/

// Get the value from a dropdown select
$( "select.foo option:selected").val();

// Get the value from a dropdown select even easier
$( "select.foo" ).val();

// Get the value from a checked checkbox
$( "input:checkbox:checked" ).val();

// Get the value from a set of radio buttons
$( "input:radio[name=bar]:checked" ).val();

改变这个

nameChoice = $("#init-name input").value; //save chosen name in nameChoice?*

到这个

nameChoice = $("#init-name input").val(); //save chosen name in nameChoice?*

还有这个

roomChoice = $("#init-room select").value; //save chosen room in roomChoice?

到这个

roomChoice = $("#init-room select").val(); //save chosen room in roomChoice?