簡體   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