Sna*_*SWE 1 javascript jquery return
我有这个代码:
function get_id_from_coords (x, y)
{
x = parseInt(x);
y = parseInt(y);
if (x < 0)
{
x = (x + 6) * 60;
}
else
{
x = (x + 5) * 60;
}
if (y < 0)
{
y = (y + 6) * 60;
}
else
{
y = (y + 5) * 60;
}
$('#planets').children().each(function(){
if ($(this).attr('x') == x) {
if ($(this).attr('y') == y) {
alert (parseInt($(this).attr('id')));
return parseInt($(this).attr('id'));
}
}
});
}
alert(get_id_from_coords(x, y));
Run Code Online (Sandbox Code Playgroud)
但是,从这段代码我得到两个弹出窗口:首先,从函数内部,我得到正确的值(如63),但是当我提醒返回值时,我只是得到了未定义.
由于函数没有返回,因此未定义 - 最后一个语句是对each
函数的调用,而不是return
语句.如果你回报,例如
...
return $('#planets').children().each(function(){
if ($(this).attr('x') == x) {
if ($(this).attr('y') == y) {
alert (parseInt($(this).attr('id')));
return parseInt($(this).attr('id'));
}
}
});
Run Code Online (Sandbox Code Playgroud)
它将返回一些东西 - 在这种情况下,基于文档:
http://api.jquery.com/jQuery.each/
The method returns its first argument, the object that was iterated.
Run Code Online (Sandbox Code Playgroud)它会让孩子们回归#planets
.
如果你想找到一些专门使用的值each
,那么你可以这样做:
...
val toRet;
$('#planets').children().each(function(){
if ($(this).attr('x') == x) {
if ($(this).attr('y') == y) {
toRet = parseInt($(this).attr('id'));
}
}
});
return toRet;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
914 次 |
最近记录: |