javascript jquery Uncaught SyntaxError: Illegal break statement
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31673494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery Uncaught SyntaxError: Illegal break statement
提问by Puni
Uncaught SyntaxError: Illegal break statement
未捕获的语法错误:非法中断语句
This is the warning i got when i try to break of the loop. What I want to do break of the loop when the condition is meet.In the example code I have two active class where I want to break out of the loop completely when the first active class is encountered.
这是我尝试中断循环时收到的警告。当条件满足时我想做的循环中断。在示例代码中,我有两个活动类,当遇到第一个活动类时,我想完全跳出循环。
<ul>
<li id="foo1" class="bar">1</li>
<li id="foo2" class="bar">2</li>
<li id="foo3" class="bar">3</li>
<li id="foo4" class="bar">4</li>
<li id="foo5" class="active">5</li>
<li id="foo6" class="bar">6</li>
<li id="foo7" class="bar">7</li>
<li id="foo8" class="active">8</li>
</ul>
js
js
$(function(){
function setup(){
var x,y,z;
$("ul li").each(function(){
//console.log($(this)[0].className);
if($(this)[0].className === 'active'){
x = $(this)[0].className;
y = $(this)[0].tagName;
z = $(this)[0].id;
break;
}
});
var return_values = {
class : x,
tag : y,
id : z
}
return(return_values);
}
var data = setup();
console.log(data.class,data.tag,data.id);
});
JSFIDDLE here
JSFIDDLE在这里
回答by Rory McCrossan
To exit the anonymous function in the each()
use return false
. Also note that using a DOMElement to create a jQuery object to then access properties of the DOMElement is entirely redundant. Try this:
要退出的匿名函数each()
使用return false
。另请注意,使用 DOMElement 创建 jQuery 对象然后访问 DOMElement 的属性是完全多余的。试试这个:
$("ul li").each(function() {
if (this.className === 'active') {
x = this.className;
y = this.tagName;
z = this.id;
return false;
}
});