繁体   English   中英

在动态创建的html中调用javascript函数

[英]call a javascript function within dynamically created html

我有一个Java脚本文件,如下图所示。
在此文件中,我为网页创建一个html代码,并在此html中调用Java脚本文件中定义的函数。 但是当我运行它时,我得到的是函数未定义。
附加信息 :

http://s8.postimg.org/nqwv1na6d/js_function.png

http://s1.postimg.org/mqyu5zalr/js_function.png

加上提到的函数(“ cButton”)是在Java脚本文件中的另一个函数中定义的。

(function () {
    var thecid = 0;

    function cButton (ii) {
        document.getElementById(ii).style.display = 'none';
        alert('fdgfg');
    }

    $("#subber").on("click", function () {
        var thelm = "#c0"+thecid;
        var newcommhtml = '<div id="c0' + thecid + '" class="cnew clearfix">';
        var ii='c0'+thecid;
        newcommhtml += '<section class="c-content">';
        newcommhtml += '<a href="#" onclick="cButton(\'' + ii + '\');" style="color:black;">x</a>';
        newcommhtml += '<p>' + nl2br(textval) + '</p> </section></div>';        
    });
})()

为了使onclick起作用,您需要cButton()作为全局窗口对象的属性可全局访问。

将您的代码更改为:

window.cButton = function(ii) {
   ...
}

问题是您在文档就绪处理程序中定义了cButton ,因此它不在此范围内。 如果您在外部声明该函数,则以后可以访问它了。

function cButton(ii){
    document.getElementById(ii).style.display = 'none';
    alert('fdgfg');
}

(function(){
    var thecid = 0;
    $("#subber").on("click", function(){
        var thelm = "#c0"+thecid;
        var newcommhtml = '<div id="c0'+thecid+'" class="cnew clearfix">';
        var ii='c0'+thecid;
        newcommhtml += '<section class="c-content">';
        newcommhtml += '<a href="#" onclick="cButton(\''+ii+'\');" style="color:black;">x</a>';
        newcommhtml += '<p>'+nl2br(textval)+'</p> </section></div>';        
    });
})()

暂无
暂无

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

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