我有这个代码:
<input type="hidden" id="editorTitle" name="title" value="home">
<textarea name="text" id="editorText"></textarea>
但是当我写
$('#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);
});
但是有什么问题吗?!?!
您应该在文档准备好后调用事件,如下所示:
$(document).ready(function () {
// Your code
});
这是因为您试图在浏览器渲染元素之前对其进行操作。
所以,在您发布的情况下,它应该看起来像这样
$(document).ready(function () {
var editorTitle = $('#editorTitle').val();
var editorText = $('#editorText').html();
});
希望有帮助。
提示:始终将 jQuery 对象保存在变量中以供以后使用,并且只有在文档加载后真正需要运行的代码才应放入 read() 函数中。
$(document).ready(function () {
//your jQuery function
});
但它仍然不起作用,并且返回
undefined
值。 我检查我的 HTML DOM
<input id="username" placeholder="Username"></input>
我意识到我在 jQuery 中引用了它是错误的:
var user_name = $('#user_name').val();
制作:
var user_name = $('#username').val();
解决了我的问题。
所以最好检查一下你以前的代码。
$(document).ready(function () {
//your jQuery function
});
如何命名 ID。
<input id="user_info[1][last_name]" ..... />
var last_name = $("#user_info[1][last_name]").val() // returned undefined
卸下支架解决了问题:
<input id="user_info1_last_name" ..... />
var last_name = $("#user_info1_last_name").val() // returned "MyLastNameValue"
无论如何,对于某些人来说可能是理所当然的,但如果这对其他人有帮助......就这样吧!
:-) - 德鲁
$()
包裹您的物体
var tableChild = children[i];
tableChild.val("my Value");// this is wrong
正确的是
$(tableChild).val("my Value");// this is correct
$('#editorTitle').attr('value')
?