如何在另一个函数中使用一个函数的变量?我知道这已被问及并回答,但我无法将这些解决方案应用于我的特定代码。 Accessing variables from other functions without using global variables How to get a variable returned across multiple functions - Javascript/jQuery我正在https://github.com/icatcher-at/MP3RecorderJS使用名为MP3RecorderJS的库。在demo html页面上有以下代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>MP3 Recorder test</title>
</head>
<body id="index" onload="">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="mp3recorder.js"></script>
<script type="text/javascript">
var audio_context;
function __log(e, data) {
log.innerHTML += "\n" + e + " " + (data || '');
}
$(function() {
try {
// webkit shim
window.AudioContext = window.AudioContext || window.webkitAudioContext;
navigator.getUserMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
window.URL = window.URL || window.webkitURL;
var audio_context = new AudioContext;
__log('Audio context set up.');
__log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
} catch (e) {
alert('No web audio support in this browser!');
}
$('.recorder .start').on('click', function() {
$this = $(this);
$recorder = $this.parent();
navigator.getUserMedia({audio: true}, function(stream) {
var recorderObject = new MP3Recorder(audio_context, stream, { statusContainer: $recorder.find('.status'), statusMethod: 'replace' });
$recorder.data('recorderObject', recorderObject);
recorderObject.start();
}, function(e) { });
});
$('.recorder .stop').on('click', function() {
$this = $(this);
$recorder = $this.parent();
recorderObject = $recorder.data('recorderObject');
recorderObject.stop();
recorderObject.exportMP3(function(base64_mp3_data) {
var url = 'data:audio/mp3;base64,' + base64_mp3_data;
var au = document.createElement('audio');
au.controls = true;
au.src = url;
$recorder.append(au);
recorderObject.logStatus('');
});
});
});
</script>
<div class="recorder">
Recorder 1
<input type="button" class="start" value="Record" />
<input type="button" class="stop" value="Stop" />
<pre class="status"></pre>
</div>
<div class="recorder">
Recorder 2
<input type="button" class="start" value="Record" />
<input type="button" class="stop" value="Stop" />
<pre class="status"></pre>
</div>
<pre id="log"></pre>
</body>
</html>
在第56行,有变量 var url ='data:audio / mp3; base64,'+ base64_mp3_data;
如果我写一个新功能,如:
function testing() {
console.log(url)
}
如何将var url导入我的“测试”功能?为了使它工作,我创建了一个隐藏的div,使innerhtml等于var url,然后在我的第二个函数中引用该div。但这似乎非常hackish。
答案 0 :(得分:-1)
只需在函数外声明变量,如下所示:
var url;
然后,当你更新函数中的变量时,它的值将被简单地更新,并且它将可用于其他函数。
var hello;
function changeVar() {
hello = 'hello';
}
function displayVar() {
alert(hello);
}
&#13;
<button onclick="changeVar()">Change the variable to "hello"</button>
<br/>
<button onclick="displayVar()">Display the variable's value</button>
&#13;