0

这是一个 JSfiddle。http://jsfiddle.net/ZttnJ/5/

问题是我只需要一个范围内的变量可以访问另一个范围,但是如果我将变量放在更高的范围内,它会破坏元素的动态创建。这似乎是动态创建的 dom 元素和我很好奇是否有一种样板方法来解决这个问题,而无需将代码重新创建到带有原型或其他东西的构造函数中。为了清楚起见,我评论了代码。只有一条评论。

var SynthCreationModule = (function(){


context = new webkitAudioContext(); 
var orangeButton;
var applicationArea = document.getElementById("applicationArea"),
orangeButton = document.getElementById("orangeButton"),         
counterSynth = 1;
counterSynthMuteButton = 1;
counterSynthParameters = 1;
counterPitchInput = 1;
orangeButton.addEventListener("click",createSynth, false);     



function createSynth () {
    var pitchInput = document.createElement('input').value; // I need this to be accessible to the function called synth.onmousedown
    pitchInput.type = "range";
    pitchInput.className  = "pitchInputClass";
    pitchInput.id = "pitchInput" + (counterPitchInput++);   
    var synth = document.createElement("div"); 
    synth.className  = "synth";                        
    synth.id = "synth" + (counterSynth++);
    var synthMute = document.createElement("div");
    synthMute.className  = "synthMute";   
    synthMute.id = "synthMute" + (counterSynthMuteButton++);
    applicationArea.appendChild(synth);
    synth.appendChild(synthMute);
    synth.appendChild(pitchInput);
    $(synth).draggable({ snap: true });
    $(synth).draggable({ grid: [ 20,20 ]});



    synth.onmousedown= function () {
    oscillator = context.createOscillator(), 
    oscillator.type = 2;  
    oscillator.frequency.value = pitchInput;                   
    oscillator.connect(context.destination);  
    oscillator.noteOn(0); 


    };

    synth.onmouseup = function ()    {  
    oscillator.disconnect(); 

    };
4

1 回答 1

0

答案是像这样修改上面的代码:

function createSynth () {

    var pitchInput = document.createElement('input');
    pitchInput.type = "range";
    pitchInput.className  = "pitchInputClass";
    pitchInput.id = "pitchInput" + (counterPitchInput++);  
    var synth = document.createElement("div"); 
    synth.className  = "synth";                          
    synth.id = "synth" + (counterSynth++);

    var synthMute = document.createElement("div");
    synthMute.className  = "synthMute";   
    synthMute.id = "synthMute" + (counterSynthMuteButton++);
    applicationArea.appendChild(synth);
    synth.appendChild(synthMute);
    synth.appendChild(pitchInput);
    $(synth).draggable({ snap: true });
    $(synth).draggable({ grid: [ 20,20 ]});


  synth.addEventListener("mousedown",playSynth, false);

function playSynth() {
//var pitchState = document.getElementById('oscPitch1').value;
oscillator = context.createOscillator(),  // Creates the oscillator 
oscillator.type = 2;  
oscillator.frequency.value = pitchInput.value;                   
oscillator.connect(context.destination);  // Connects it to output
oscillator.noteOn(0); 


};
于 2013-01-12T07:59:23.890 回答