javascript动态函数调用undefined

时间:2012-08-09 11:34:06

标签: javascript jquery

函数savefromtextarea()& varialbe globe未定义,单击保存按钮时调用...

我的代码的这一部分...我需要在单击保存文本按钮时从texarea方法访问保存...当我尝试调用saveFromTextArea方法时,它的throws globe是未定义的但是globe变量是全局变量...

    ME.ZFP.annotaion.Text = function () { //function to annotate the text

var canvas = myscreen.getTempCanvas().ele;
var context = canvas[0].getContext('2d');
var global = this;

$(canvas).mousedown(function(e){ //on mouse down event 

    if ($('#textAreaPopUp').length === 0) {

        var mouseX = e.pageX - this.offsetLeft + $(canvas).position().left;
        var mouseY = e.pageY - this.offsetTop;

        //append a text area box to the canvas where the user clicked to enter in a comment
        var textArea = "<div id='textAreaPopUp' style='position:absolute;top:"+mouseY+"px;left:"+mouseX+"px;z-index:30;'><input type='text' id='textareaTest' ></input>";
     //Click on save buttom global.saveTextFromArea undefined
        var saveButton = "<input type='button' value='save' id='saveText' onclick='global.saveTextFromArea("+mouseY+","+mouseX+");'></div>";
        var appendString = textArea + saveButton;
        $("#container").append(appendString);
    } 
});
//Function to be called 
this.saveTextFromArea = function(y,x){
        //get the value of the textarea then destroy it and the save button
        var text = $('textarea#textareaTest').val();
        $('textarea#textareaTest').remove();
        $('#saveText').remove();
        $('#textAreaPopUp').remove();

}

   }

由于 阿然

2 个答案:

答案 0 :(得分:0)

您的代码有一些错误,已在this fiddle中修复 您在代码的最后忘记了}); 最后(挑剔)我纠正了:
if ($('#textAreaPopUp').length == 0)
if ($('#textAreaPopUp').length === 0)

但是......这个纠正的代码能解决你的问题吗?

答案 1 :(得分:0)

onclick='...'这样的内联事件处理程序只能引用全局范围的变量和函数,但如果在函数内部声明了名为global的变量(例如,在document.ready处理程序中),那么它不是全局的,并且内联属性事件处理程序无法看到它。