jquery - возвращает значение из функции - PullRequest
0 голосов
/ 16 мая 2011

говорят, что у меня есть следующая функция:

function checkPanes() {
    activePane = '';
    var panels = $("#slider .box .panel");

    panels.each(function() {

    //find the one in visible state.
    if ($(this).is(":visible")) {
    activePane = $(this).index()+1;
    console.log(activePane);
    }

    });
} //END checkPanes();

В идеале, я бы хотел вызвать для этой функции в другом месте (скорее всего, из другой функции) и извлечь значение IВ настоящее время вывод на консоль.

(пример ..)

function exampleCase() {
    checkPanes(); //evidently, does not return anything. 
    //Ideally, I want the numerical value, being output to console in above function.
}  

Заранее спасибо!Все предложения / комментарии приветствуются.
Приветствия

Ответы [ 7 ]

4 голосов
/ 16 мая 2011

только что заметил петлю; похоже, что вы, возможно, захотите вернуть массив всех активных панелей (поскольку в теории их может быть больше одной).

function checkPanes() {
    activePanes = [];
    var panels = $("#slider .box .panel");

    panels.each(function() {

    //find the one in visible state.
    if ($(this).is(":visible")) {
    activePane.push($(this).index()+1);
    console.log(activePane);
    }

    });
    return activePanes;
} 

Если вы знаете, что будет только один активный, вы можете вернуться к исходному подходу и просто добавить return activePane после console.log.

2 голосов
/ 16 мая 2011

Забудьте всех, кто говорит return activePane, так как они не видели, что это в цикле jQuery each.Не сработает.

Я бы предложил реструктурировать ваш селектор.Селектор, который вы должны использовать: $("#slider .box .panel:visible").Это полностью отрежет каждую вашу петлю.Например, вы можете изменить структуру кода следующим образом:

function checkPanes() {
    return $("#slider .box .panel:visible").index();
}

function exampleCase() {
    var visiblePane = checkPanes();

    // ... do something with the index
}

Я бы предложил просто использовать встроенный селектор, а не создавать новую функцию, но это дело вкуса, особенно если вам нужно выбратьодна и та же вещь в нескольких местах.

0 голосов
/ 16 мая 2011

Вы можете сохранить свой код и просто добавить возврат, если хотите использовать значения где-то еще

function checkPanes() {
 activePane = '';
 var panels = $("#slider .box .panel");

  panels.each(function() {

  //find the one in visible state.
  if ($(this).is(":visible")) {
  activePane = $(this).index()+1;
  console.log(activePane); //Logs to console.
  return activePane; //Returns value also.
}

});
} 

Так что здесь вы можете использовать возвращаемое значение или просто записать его в консоль. Вот как я понял твой вопрос

function exampleCase() {
    checkPanes(); //Now it will still write in console. but you dont need to use the return

    alert(checkpanes()); //Would write it to console and to an alert!
} 

Но убедитесь, что вы возвращаете строку - или конвертируете в строку, если хотите отключить ее где-нибудь в виде текста.

0 голосов
/ 16 мая 2011

вы должны вернуть что-то внутри первой функции, чтобы манипулировать ею внутри второй:

function checkPanes() {
    activePane = '';
    var panels = $("#slider .box .panel");
    //create a return array
    visiblePanels = [];
    panels.each(function() {

    //find the one in visible state.
    if ($(this).is(":visible")) {
    activePane = $(this).index()+1;
    //add the result to the returnb array
    visiblePanels[] = activePane
    }
    });
    // return results
    return visiblePanels;
}

function exampleCase() {
    var thepane = checkPanes();
    //now it has all the visible panels that were founded in the other function
    // you can access them with thepane[0] or iterate on them

}  

Я думаю, это то, что вам нужно.

0 голосов
/ 16 мая 2011

Это:

function checkPanes() {
  activePane = '';
  var panels = $("#slider .box .panel");

  panels.each(function() {

  //find the one in visible state.
  if ($(this).is(":visible")) {
  activePane = $(this).index()+1;
  }

  });
  return activePane;
} //END checkPanes();

и это:

function exampleCase() {
   var myval=checkPanes(); //evidently, does not return anything. 
   console.log(myval);

}

0 голосов
/ 16 мая 2011

Я думаю, что это так же просто, как использовать return activePane;

0 голосов
/ 16 мая 2011

Просто переключите консольную строку на оператор возврата:

function checkPanes() {
    activePane = '';
    var panels = $("#slider .box .panel");

    panels.each(function() {

    //find the one in visible state.
    if ($(this).is(":visible")) {
        activePane = $(this).index()+1;
        return activePane; // Return the value and leave the function
    }

    });
} //END checkPanes();

Для звонка:

function exampleCase() {
    var thepane = checkPanes(); //evidently, does not return anything. 
    // ...
}  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...