jQuery .each循环字符串或对象

为什么这不起作用?

$( ["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'); 它按预期工作?

console.log(typeof opt)生成string和期望值。

—更新—

我刚刚看到html通过ajax写入页面并在.ready()上执行:(感谢所有人的帮助,非常感谢。

如果页面未完全加载且#rb-blog尚未可用,则会出现什么问题。

 $(document).ready(function(){ $( ["blog","user","forum"] ).each(function(num,opt) { if ( window.location.pathname.indexOf(opt) != -1 ) { $('#rb-' + opt).attr('checked','checked'); return false; } }); }); 

正如评论中已经提到的, return false实际上将退出“blog”,“user”,“forum”循环,因此一旦pathname.indexOf条件为真,就停止检查复选框。

您还可以添加console.log(window.location.pathname); 确保此变量包含您正在检查的内容。 也许这是一个套管问题?

如果您想知道路径名中存在哪些文字,您可以使用:

 var isPresent = []; $( ["blog","user","forum"] ).each(function(num,opt) { if ( window.location.pathname.indexOf(opt) != -1 ) { $('#rb-' + opt).attr('checked','checked'); isPresent.push(opt); } }); 

如果您只想知道路径名中是否存在其中一个文字:

 var isAtLeastOneIsPresent = false; $( ["blog","user","forum"] ).each(function(num,opt) { if ( window.location.pathname.indexOf(opt) != -1 ) { $('#rb-' + opt).attr('checked','checked'); isAtLeastOneIsPresent = true; } }); 

解决方案:HTML内容尚未写入页面,所以现在我们等待ajax请求完成,然后我们调用函数来更新选择值,就像这样……

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

也许这可以让别人头疼!

—编辑—

被警告! 与CakePHP一起使用时,此解决方案引起了严重的问题。 当我们在页脚中调用此函数时,布局消失了。

看到这个post: CakePHP后退和前进按钮没有布局