简体   繁体   English

函数中的Onclick事件无法调用嵌套函数

[英]Onclick event in a function not able to call nested function

I have a function which has another function in it. 我有一个功能,其中有另一个功能。 There is an onclick event in main function and I want it to call the inner function. 主函数中有一个onclick事件,我希望它调用内部函数。 However when I click the element, it says that the function is not defined. 但是,当我单击该元素时,它表示未定义函数。 The onclick event is in a for loop. onclick事件处于for循环中。 Here is the code: 这是代码:

function renk(){
        function metinRenginiDegistir(boya){
            //seciliMetinDegistir("<font color='"+boya+"'>"+seciliMetin()+"</font>");
            alert("a");
        }
        var sagic;
        var renkler=new Array("#000000","#FF0000","#00FF00","#0000FF","#FFFF00","#00FFFF","#FF00FF","#666666");
        var adlar=new Array("Siyah","Kırmızı","Yeşil","Mavi","Sarı","Turkuaz","Magenta","Gri");
        for(i=0;i<renkler.length;i++){
            sagic=sagic+"<tr><td><div **onclick='metinRenginiDegistir(this.style.background)'** style='cursor:pointer;width:28px;height:28px;background:"+renkler[i]+";margin-left:17px;'></div></td><td>"+adlar[i]+"</td><td>"+renkler[i]+"</td></tr>";
        }
        sagic="<center><table id='renklerinTablosu'><tr><th>Önizleme&nbsp;&nbsp;</th><th>Renk Adı&nbsp;&nbsp;</th><th>Renk Kodu</th></tr>"+sagic+"</table></center>";
        sag.innerHTML=sagic.replace("undefined","");
        //document.getElementById("renklerinTablosu").getElementsByTagName("div").onclick=function(){alert("a");}
        // onclick='metinRenginiDegistir(this.style.background)'
    }

They're correct, you can't reach metinRenginiDegistir() because its not within scope. 他们是正确的,您无法到达metinRenginiDegistir(),因为它不在范围内。 what you can do, is re-write 'function metinRenginiDegistir()' as 'this.metinRenginiDegistir = function(){}.bind(this);'. 您可以做的是将“ function metinRenginiDegistir()”重写为“ this.metinRenginiDegistir = function(){}。bind(this);”。 Now, set your variable 'onclick' to 'this.metinRenginiDegistir()', (only if your setting it within 'renk()') or, outside of 'renk'()', set a variable equal to an instanciation of renk() and use that: 现在,将变量“ onclick”设置为“ this.metinRenginiDegistir()”(仅当您将其设置在“ renk()”之内)或在“ renk”()之外时,才将变量设置为等于renk的实例化。 ()并使用:

var renkInstance = new renk();

...onclick = renkInstance.metinRenginiDegistir;

You can't reach 'metinRenginiDegistir' from outside of 'renk()', but you can reach 'metinRenginiDegistir' from 'renk()'s scope using your instanciation of 'renk()', renkInstance. 您无法从'renk()'的外部访问'metinRenginiDegistir',但是可以使用实例化'renk()',renkInstance从'renk()的范围访问'metinRenginiDegistir'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM