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

时间:2014-03-06 09:34:56

标签: javascript jquery 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>';        
    });
})()

2 个答案:

答案 0 :(得分:4)

要使onclick生效,您需要将cButton()作为全局窗口对象的属性进行全局访问。

将您的代码更改为:

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

答案 1 :(得分: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>';        
    });
})()