2015-05-30 52 views
2

如何将变量传递给匿名函数。我想将几个变量传递给一个匿名函数,基于这个函数,它会创建一个新的字符串。 在这段代码中,我想传递url,时间戳,id和计划。如何在jQuery中的匿名函数中获取变量?

<script> 
     jQuery(document).ready(function() { 
      console.log("check") 
      var newUrl=url+'?id='+id+'&timestamp='+timestamp+'&plan='+plan; 
      console.log(newUrl); 
      createStoryJS({ 
       type:  'timeline', 
       width:  '1250', 
       height:  '240', 
       source:  newUrl, 
       embed_id: 'my-timeline' 
      }); 
     }); 
    </script> 
+0

哪里是匿名函数? – Satpal

+0

@Satpal抱歉,我是JS新手。我试图在函数()中传递一些变量。 –

+0

好吧,从哪里,你是如何通过它 – Satpal

回答

1

的参数到准备处理程序的jQuery传递和被设置为jQuery对象(见https://api.jquery.com/ready/>混叠的jQuery命名空间)。所以你不能将它传递到上面代码中的函数声明中。

您可以将其设置为全局对象或设置表单域,然后从函数内部读取它。小提琴后者 - http://jsfiddle.net/eqz7410c/

HTML

<form> 
    <input id="b" type="hidden" value="123" /> 
</form> 

JS

$(document).ready(function() { 
    alert($("#b").val()) 
}); 
1

你可以声明具有全局范围的变量,并使用它的函数调用内部如下

var globalVar = 1; 
jQuery(document).ready(function() { 
    console.log(globalVar); 
}); 
0

首先,jQuery(document).ready(function() {});会是文件的入口点准备好被访问。这有几种方法。

的想法是,你并不需要通过任何东西,但使用您创建的资源在这个匿名函数。

我想几个变量传递给一个匿名函数,基础上, 功能,它会创建一个新的字符串。

我不建议你使用全局变量。该函数从中可能得到这些值idtimestamp和​​应该返回你刺本身,你可以分配给newUrl文件准备函数内部。您也可以使用closure

function returnUrl(){ 
    // code to calculate id, timestamp and path.. 
    // .... 
    // .... 
    return url+'?id='+id+'&timestamp='+timestamp+'&plan='+plan; 
} 

jQuery(document).ready(function() { 
// DOM ready to access.. 
    console.log("check") 
    var newUrl = returnUrl(); 
    console.log(newUrl); 
    createStoryJS({ 
     type:  'timeline', 
     width:  '1250', 
     height:  '240', 
     source:  newUrl, 
     embed_id: 'my-timeline' 
    }); 
}); 
相关问题