[英]How do I assign the result of a function into a global variable?
我不知道如何將該函數的結果分配給全局變量。 我知道這是很基本的事情,但是有人可以幫忙嗎?
var pixel_code = null
function captureValue(){
pixel_code = document.getElementById("baseText").value;
return pixel_code;
}
pixel_code = captureValue();
您正在函數內外重用pixel_code,這不是一個很好的模式,但是您顯示的代碼應該可以正常工作。 您看到什么錯誤? 您未顯示的代碼周圍是什么代碼? 所有這些都可以嵌套在另一個函數中嗎? (感謝@JosephSilver的點頭。)
如果頁面重新加載,您的變量將被重置為其初始狀態。
請嘗試一下
var pixel_code='';
function captureValue(){
return document.getElementById("baseText").value;
}
function getValueBack()
{
pixel_code = captureValue();
//alert(pixel_code); /* <----- uncomment to test -----<< */
}
感謝您分享您嘗試的jsfiddle。 我明白了。 captureValue()函數是異步運行的,因此定義它后不久的console.log()
還沒有值。 我已經剝去了jsfiddle並提出了這個工作示例:
<html>
<head>
</head>
<body>
<h1>Welcome to the AdRoll SandBox</h1>
<textarea id="baseText" style="width:400px;height:200px"></textarea><br />
<input type="button" value="test" id="text_box_button" onclick="captureValue()"/>
<input type="button" value="get" id="text_box_button2" onclick="getValue()"/>
<script>
var pixel_code = null;
function captureValue(){
pixel_code = document.getElementById("baseText").value;
return false;
}
function getValue() {
alert(pixel_code);
return false;
}
</script>
</body>
</html>
我添加了第二個按鈕。 在文本框中輸入內容,按“測試”(設置值),然后按“獲取”以獲取全局變量的值。
這是使用jQuery和閉包來避免全局變量的同一示例:
<html>
<head>
</head>
<body>
<h1>Welcome to the AdRoll SandBox</h1>
<textarea id="baseText" style="width:400px;height:200px"></textarea><br />
<input type="button" value="test" id="text_box_button" />
<input type="button" value="get" id="text_box_button2" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
var pixel_code = null;
$("#text_box_button").click(function (){
pixel_code = document.getElementById("baseText").value;
return false;
});
$("#text_box_button2").click(function () {
alert(pixel_code);
return false;
});
});
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.