在动态创建的HTML中调用JavaScript函数

3
我有一个 JavaScript 文件,如下图所示。在这个文件中,我为我的网页创建了一个 HTML 代码,并在这个 HTML 中调用了一个在 JavaScript 文件中定义的函数。但是当我运行它时,我得到了函数未定义的错误。
附加信息:

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

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

此外,提到的函数 ("cButton") 在 JavaScript 文件中的另一个函数中被定义。
(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>';        
    });
})()

为什么要用代码的图片而不是代码本身? - techfoobar
请放置代码而不是图片。 - Vicky Gonsalves
抱歉,我以为这样更舒适。 - saeed hardan
2个回答

6

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

请将代码更改为:

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

是的,非常感谢。实际上,Archer建议的方法也可以,但我更喜欢这个答案,因为它更简短。 - saeed hardan

1
问题在于你正在文档就绪处理程序中定义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>';        
    });
})()

这个行得通,谢谢你。不过我还是得选Techfoobar的答案,因为它更短 :) - saeed hardan
没问题 - 很高兴你解决了它。我只是想进一步解释一下 :) - Reinstate Monica Cellio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接