jQuery val是未定义的?

The*_*hew 13 html javascript jquery undefined

我有这个代码:

<input type="hidden" id="editorTitle" name="title" value="home">
<textarea name="text" id="editorText"></textarea>
Run Code Online (Sandbox Code Playgroud)

但是,当我写,$('#editorTitle').val()并且$('#editorText').html(),$('#editorTitle').val()'未定义'并且$('#editorText').html()是空的?

怎么了?


编辑:

这是我的完整代码:

function openEditor() {
    $("#editor").show().animate({ width: 965, height: 380 }, 1500);
    $("#editor textarea").show();
}

function closeEditor() {
    $("#editor").animate({ width: 985, height: 1 }, 1500, function () {
        $("#editor").hide();
        $("#editor textarea").hide();
    });
}

function setedit() {
    $.ajax({
        type: "POST",
        url: "engine.php",
        data: "title=" + $('#editorTitle').attr('value') + "&text=" + $('#editorText').html(),
        beforeSend: function () {
            $('#mainField').html('<img src="data/images/loader.gif" alt="Loading...">');
        },
        success: function (msg) {
            alert(msg);
            closeEditor();
            search();
        }
    });
}
function search() {
    $('#title').val($('#search').val());

    $.get('engine.php?search=' + $('#search').val(), function (data) {
        $('#mainField').html(data);
    });

    $.get('engine.php?raw=true&search=' + $('#search').val(), function (data2) {
        $('#editorText').html(data2);
    });

    $.get('engine.php?title=true&search=' + $('#search').val(), function (data2) {
        $('#h1').html(data2); // Row 152
        $('#editorTitle').html(data2);
    });
}

$(document).ready(function () {
    $("#ready").html('Document ready at ' + event.timeStamp);
});
Run Code Online (Sandbox Code Playgroud)

但是出了什么问题?!?!

Aro*_*eel 23

您可能在HTML:示例之前包含了JavaScript .

您应该在窗口加载时执行JavaScript(或者更好,在DOM完全加载时执行),或者应该 HTML 之后包含JavaScript :示例.


Jon*_*han 8

您应该在文档准备好后调用事件,如下所示:

$(document).ready(function () {
  // Your code
});
Run Code Online (Sandbox Code Playgroud)

这是因为您尝试在浏览器呈现元素之前对其进行操作.

所以,如果你发布它应该看起来像这样

$(document).ready(function () {
  var editorTitle = $('#editorTitle').val();
  var editorText = $('#editorText').html();
});
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.

提示:始终将jQuery对象保存在变量中供以后使用,只有在文档加载后真正需要运行的代码才能进入ready()函数.


fWd*_*d82 5

这很愚蠢,但供将来参考。我确实把我所有的代码都放在了:

$(document).ready(function () {
    //your jQuery function
});
Run Code Online (Sandbox Code Playgroud)

但它仍然无法正常工作,并且正在返回undefined值。我检查我的 HTML DOM

<input id="username" placeholder="Username"></input>
Run Code Online (Sandbox Code Playgroud)

我意识到我在 jQuery 中引用它是错误的:

var user_name = $('#user_name').val();
Run Code Online (Sandbox Code Playgroud)

进行中:

var user_name = $('#username').val();
Run Code Online (Sandbox Code Playgroud)

解决了我的问题。

所以最好检查你以前的代码。