我有一个这样的函数:
$(document).ready(function () {
listproject() ;
});
listproject()
是一个返回我已附加到文档中的无序列表字符串的函数。
到这里一切都好。我的 HTML View 中有正确的列表。
就在listproject()
之后我添加了一个代码行来显示我的第一个 <li>
值,但我的结果未定义。
$(document).ready(function () {
listproject() ;
alert($('li:first').val());
});
如果我登录到 JavaScript 控制台并选择监视表达式,我的 jQuery 对象 $('li:first')
存在。
这是我根据您的请求在列表项目中返回的字符串
<ul><li id="205">205<ul><li id="206">206<ul><li id="208">208</li><li id="209">209</li><li id="211">211<ul><li id="212">212</li><li id="213">213</li></ul></li></ul></li><li id="207">207<ul><li id="210">210</li></ul></li></ul></li></ul>
我将此返回附加到我的 html 代码中的现有 div 中,这就是我的 listproject() 函数的作用,结果是好的。
编辑:
在您的请求之后,这里是我的函数 listproject() ,后面是 makeTree 函数,它返回无序列表的字符串给 listproject() :
function listproject() {
$.post("/portail/project/home/getProjectList",
function (d) {
var pl = $("#tree").empty();
if (d.length == 0) {
pl.append($("<div>").addClass("align_center").html("there is no project"));
return;
}
pl.append(makeTree(d,0));
},
"json"
);
}
function makeTree( a,level) {
r = '' ;
for ( i in a ) {
if (a[i]['parentid'] == level ) {
r = r + '<li id='+'"'+a[i]['id']+'"'+'>'+ a[i]['name'] + makeTree(a,a[i]['id'] ) + '</li>';
}
}
if (r==''){r=''; }
else { r= '<ul>' + r + '</ul>' ;}
return r;
}
现在您已经具备了做出回应并再次思考的所有要素。
最佳答案
我怀疑 $('li:first')
部分有效,但 .val()
位无效。它们应该用于表单项,例如复选框和选择。请参阅.val()
documentation .
尝试 $('li:first').text()
或 $('li:first').html()
编辑:您仍然收到未定义错误的原因是您的列表元素附加在 AJAX 请求中。顾名思义,这是异步完成的,在 POST 完成之前调用警报。
因此,您需要一种方法来确保在 post 调用完成后调用警报。基本方法是作为您传入的匿名函数的一部分:
function listproject() {
$.post("/portail/project/home/getProjectList",
function (d) {
/* [your existing code here] */
// That's all done, so now I can query it...
alert($('li:first').text());
}
});
}
或者使用deferred (好多了):
function listproject() {
$.post("/portail/project/home/getProjectList",
function (d) {
/* [your existing code here] */
}
}).done(function() {
// That's all done, so now I can query it...
alert($('li:first').text());
});
}
这里的另一个调整是,您可以使 listproject 返回延迟的并且可以在该函数之外使用:
function listproject() {
var deferred = $.post("/portail/project/home/getProjectList",
function (d) {
/* [your existing code here] */
}
});
return deferred;
}
var deferred = listproject();
deferred.done(function() {
// That's all done, so now I can query it...
alert($('li:first').text());
});
关于jquery - 文档准备好后无法选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18231708/