Javascript返回不工作
我有以下代码:Javascript返回不工作,javascript,jquery,return,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; }
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));
函数从坐标(x,y)获取id
{
x=parseInt(x);
y=parseInt(y);
if(x<0)
{
x=(x+6)*60;
}
其他的
{
x=(x+5)*60;
}
if(y<0)
{
y=(y+6)*60;
}
其他的
{
y=(y+5)*60;
}
$('#planets').children().each(function()){
if($(this).attr('x')==x){
if($(this.attr('y')==y){
警报(parseInt($(this.attr('id'));
返回parseInt($(this.attr('id'));
}
}
});
}
警报(从坐标(x,y)获取id);
但是,从这段代码中,我得到了两个弹出窗口:
首先,从函数内部,我得到了正确的值(如63),但是,当我警告返回值时,我只是得到了未定义的值。您得到了未定义的值,因为您的函数没有返回-最后一条语句是对
每个函数的调用,而不是返回语句。如果你放了一张报税表,例如
...
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'));
}
}
});
它将返回一些内容-在本例中,根据文档:
-
它将返回#plants
的子对象
如果您想特别使用每个
查找某个值,则可以执行以下操作:
...
val toRet;
$('#planets').children().each(function(){
if ($(this).attr('x') == x) {
if ($(this).attr('y') == y) {
toRet = parseInt($(this).attr('id'));
}
}
});
return toRet;
由于函数不返回,因此未定义-最后一条语句是对每个
函数的调用,而不是返回
语句。如果你放了一张报税表,例如
...
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'));
}
}
});
它将返回一些内容-在本例中,根据文档:
-
它将返回#plants
的子对象
如果您想特别使用每个
查找某个值,则可以执行以下操作:
...
val toRet;
$('#planets').children().each(function(){
if ($(this).attr('x') == x) {
if ($(this).attr('y') == y) {
toRet = parseInt($(this).attr('id'));
}
}
});
return toRet;
x
和y
是在函数外部定义的吗?是的,它们在函数内部工作正常我很确定return
不是brokernicyrock的解决方案看起来不错-您的返回设置不正确。@SnackerSWE,对于如果(y<0){y=(y+6)*60;}否则{y=(y+5)*60;}
,考虑将其缩小为<代码> y=(yay<代码> x< /代码>和<代码> y>代码>函数外定义,是的,它们在函数内正常工作,我很确信<代码>返回< /代码>不是BROKEICICYROCK的解决方案看起来很好。您的返回没有正确设置。@ SnCalrsWe,对于<代码>(y<0){y=(y+1)* 60;}否则{y=(y+5))。* 60;}< /代码>,考虑将其缩小为<代码> y=(y+2+)(y@SnackerSWE也许你应该考虑接受这个答案?也许你应该考虑接受这个答案。