div没有在javascript中触发onclick事件

时间:2014-03-25 05:13:14

标签: javascript html

我的div元素是:

<div id="div"></div>

下面是javascript。:

function makediv() {
        var divmy = document.getElementById("div");
        var row ='';
        var color='#ccc';
        for(var i=0;i<2;i++) 
        {
divmy.innerHTML += " <div class='dynamic' id='inner"+i+"' onclick=searchFilterations(i)>"+i+"</div> ";
            color='black';
        }
    }
    function searchFilterations(e){
    alert(e);
    }

问题是:searchFilterations()函数没有在click上触发。错误是什么? 这里是小提琴: http://jsfiddle.net/cjT4s/4/

2 个答案:

答案 0 :(得分:0)

请致电makediv函数onload活动

window.onload = makediv;

function makediv() {
    var divmy = document.getElementById("div");
    var row ='';
    var color='#ccc';
    for(var i=0;i<2;i++) 
    {    

    //    divmy.innerHTML += " <div style='width: 100px;height: 30px;background-color:"+color+" ;' onclick=javascript:alert("+i+")></div> ";

         divmy.innerHTML += " <div class='dynamic' id='inner"+i+"' onclick=searchFilteration("+i+")>"+i+"</div> ";
        color='black';
    }
}
function searchFilteration(i){
alert(i);
}

FIDDLE DEMO

答案 1 :(得分:0)

使用window.searchFilteration = function (i) { ... }

尝试此操作
makediv();

function makediv() {
    var divmy = document.getElementById("div");
    var row ='';
    var color='#ccc';
    for(var i=0;i<2;i++) 
    {    
         divmy.innerHTML += " <div class='dynamic' id='inner"+i+"' onclick='searchFilteration("+i+")'>"+i+"</div> ";
        color='black';
    }
}
window.searchFilteration = function (i){
alert(i);
}

FIDDLE DEMO