jQuery val 未定义?

新手上路,请多包涵

我有这段代码:

 <input type="hidden" id="editorTitle" name="title" value="home">
<textarea name="text" id="editorText"></textarea>

But when i write $('#editorTitle').val() and $('#editorText').html() , $('#editorTitle').val() is ‘undefined’ and $('#editorText').html() is empty?

怎么了?


编辑:

这是我的完整代码:

 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);
});

但是怎么了?!?!

原文由 Thew 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 363
2 个回答

您可能在 HTML: example 之前 包含了 JavaScript。

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

原文由 Aron Rotteveel 发布,翻译遵循 CC BY-SA 2.5 许可协议

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

 $(document).ready(function () {
  // Your code
});

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

所以,在你发布的情况下,它应该看起来像这样

$(document).ready(function () {
  var editorTitle = $('#editorTitle').val();
  var editorText = $('#editorText').html();
});

希望能帮助到你。

提示:始终将您的 jQuery 对象保存在一个变量中供以后使用,只有真正需要在文档加载后运行的代码才应该放在 ready() 函数中。

原文由 Jonathan 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏