在函数内调用每个函数内的函数

时间:2012-01-03 11:36:37

标签: javascript jquery

我的语法确实存在一些小问题......这是我的代码版本......

function example1() {
    var thumbWidth = $(this).find('img').width();
    //some more code
};

function example2() {
  $('div').each(function(){
    example1();
    thumbTotal = thumbWidth + xx //etc.;
  });
};

$(document).ready(function(){
  example2();
});

我的问题是example1没有在上面的代码中执行。我已经尝试手动插入example1代码,这很好。我希望能够在其他地方调用example1,因此它在一个单独的函数中被隔离是很重要的。

非常感谢。

7 个答案:

答案 0 :(得分:8)

可能是复制和粘贴错误,但是:
第9行应为});而不是)};

这可能会导致错误的行为,因为包含语法错误的javascript代码通常仍会以某种方式解释,从而导致非常奇怪的结果。

答案 1 :(得分:1)

代码没有明显的错误(除了一些语法错误)。这个原则很好。

失败的一些可能原因:

  • 存在一些语法错误,因此没有执行任何代码。
  • jQuery选择器与任何元素都不匹配。
  • 您已重新定义了名称(例如,具有相同名称的本地变量),因此无法访问该功能。

可以通过在某处放置alert(1);来测试第一个,看看它是否显示出来。可以使用alert($('div').length);来检查第二个元素,以检查匹配的元素数量。第三个可以使用alert(example1);进行测试,看看它是否显示了函数的代码,或者是完全不同的东西。

答案 2 :(得分:1)

function example1(yo) {
  return $(yo).find('img').width();
};

function example2() {
    var total=0;
  $('div').each(function(){
    total+=example1(this);
    //Some more code here
  });
  alert(total);
};

$(document).ready(function(){
  example2();
});

这应该有用。

答案 3 :(得分:0)

示例2编写错误,更改:

  $('div').each(function(){
    example1();
    //Some more code here
  )};

通过

  $('div').each(function(){
    example1();
    //Some more code here
  });

答案 4 :(得分:0)

function example1() {
  //Code
};

function example2() {
  $('div').each(function(){
    example1();
    //Some more code here
  **});**
};

$(document).ready(function(){
  example2();
});

在example2函数中有一个错位的}}

答案 5 :(得分:0)

根据您编辑的帖子,您至少有两种方法可以解决问题:

1st:为example1()

定义一个返回值
function example1() {
    var thumbWidth = $(this).find('img').width();
    //some more code
 };
 function example2() {
  $('div').each(function() {
      thumbTotal = example1() + xx //etc.;
  });
 };
 $(document).ready(function(){
   example2();
 });

第二:为变量'thumbWidth'

定义合适的范围
    var thumbWidth;
    function example1() {
        thumbWidth = $(this).find('img').width();
        //some more code
     };
     function example2() {
      $('div').each(function() {
         //or here var thumbWidth;
         example1();     
         thumbTotal = thumbWidth + xx //etc.;
      });
     };

 $(document).ready(function(){
   example2();
 });

答案 6 :(得分:0)

认为我的问题与调用函数范围之外的变量有关。在我的情况下,这是不可能的,因为我需要变量是局部的,因为它循环遍历div(因此变量将随着每次迭代而改变)。

以下是本地变量和全局变量的解释。 http://forum.jquery.com/topic/how-do-i-declare-a-global-variable-in-jquery