2015-05-30 51 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' 
    }); 
}); 
相關問題