jQuery .each循环字符串或对象 [英] jQuery .each loop string or object
问题描述
为什么这不起作用?
$( ["blog","user","forum"] ).each(function(num,opt) {
if ( window.location.pathname.indexOf(opt) != -1 ) {
$('#rb-' + opt).attr('checked','checked');
return false;
}
});
当我输入$('#rb-blog').attr('checked','checked');
时,它能按预期工作吗?
When I input $('#rb-blog').attr('checked','checked');
it works as expected?
console.log(typeof opt)
产生string
和期望值.
-更新---
我刚刚看到html是通过ajax写入页面的,并且是在.ready()
上执行的:(感谢所有帮助,非常感谢.
I've just seen the html is being written to the page via ajax and is executed on .ready()
:( Thanks for the help all, much appreciated.
推荐答案
解决方案:HTML内容尚未写入页面,因此现在我们等待ajax请求完成,然后调用该函数以更新选择值,就像这样...
Solution: the HTML content was not yet written to the page, so now we wait for ajax requests to complete, then we call the function to update the select value, like so...
// apply checked to the selected element
function setAsChecked() {
$.each(["blog","user","forum"], function(num,opt){
if (window.location.pathname.indexOf(opt) != -1) {
$('#rb-' + opt, '.radio_menu').attr('checked','checked');
return false;
}
});
}
// $('.radio_menu').ajaxStop(function(){
// setAsChecked();
// });
// UPDATE! ajaxStop() catches all our ajax events - not cool. Instead, use when
$.when( $.ajax("") ).done(function(){
setAsChecked();
});
也许这可以使别人免于头痛!
Maybe that saves someone else a headache!
-编辑--
被警告!与CakePHP一起使用时,此解决方案引起了严重的头痛.当我们在页脚中调用此函数时,布局消失了.
BE WARNED! This solution caused a major headache when used with CakePHP. The layout disappeared when we called this function in the footer.
查看此线程: CakePHP在后退和前进按钮上没有布局
这篇关于jQuery .each循环字符串或对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!