【问题标题】:How to add onclick attribute on the fly?如何动态添加 onclick 属性?
【发布时间】:2014-01-07 19:35:14
【问题描述】:

我尝试过以下一种el.setAttribute("onclick","alert("+color['R'][i]+")");,但无法在 IE 旧版浏览器中运行。

function r_loadResources(color) {
    var rows='';    
    var index =1;
    container = document.getElementById('color_table');
    for(i=0;i<color['R'].length;i++) {  
    if(I%8==0) {
        rows = document.createElement('tr');
        rows.setAttribute("id","row"+i);
        container.appendChild(rows);    
    }
    if(document.getElementById('row'+i))
    rowids = document.getElementById('row'+i);

    var el = document.createElement('td');
    el.bgcolor = color['hex_value'][i]);
    el.setAttribute("height",'20px');
    el.setAttribute("width",'10px');
    el.setAttribute("onclick","alert("+color['R'][i]+")");
    //el.setAttribute("onmouseover","Tip('"+color['color_name'][i]+"');");
    //el.setAttribute("onmouseout","UnTip();");
    rowids.appendChild(el); 
    }
}

HTML代码是&lt;table&gt;&lt;tbody id="color_table"&gt;&lt;/tbody&gt;&lt;/table&gt;

变量

var color = new Array();
color["color_name"]= new Array("Fire Red","Tomato Red","Magenta","Orange","Yellow","Beige Yellow","Kelley Green","Forest Green","Teal Blue","Process Blue","Royal Blue","Navy Blue","Pastel Purple","Osha Purple","Deep Purple","Burgundy","Light Brown","Dark Brown","Beige","Gold","Silver","Dark Grey","Black","White","Blue","Green","Yellow2");
 color["R"]= new Array("195","218","221","231","252","255","0","0","0","0","0","5","129","140","90","110","116","75","238","183","194","114","31","255","0","37","255");
color["G"]= new Array("38","37","19","120","219","252","154","97","153","175","68","44","109","46","26","29","78","51","227","148","193","112","26","255","61","169","198");
color["B"]= new Array("31","29","123","23","0","184","80","47","152","239","129","81","165","126","116","38","42","31","198","65","193","111","23","255","107","55","30");
color["hex_value"]= new Array("#c3261f","#da251d","dd137b","#e77817","#fcdb00","#fffcb8","#009a50","#00612f","#009998","#00AFEF","#004481","#052c51","#816da5","#8c2e7e","#5a1a74","#6e1d26","#744e2a","#4b331f","#ede3c6","#b79441","#c2c2c1","#72706f","#1f1a17","#ffffff","#003d6b","#25a937","#ffc61e");

输出应该是 ![在此处输入图像描述][1] [1]:http://i.stack.imgur.com/2u1Qx.jpg

【问题讨论】:

  • 不要使用 setAttribute 添加事件处理程序!
  • 什么不完全有效?
  • 你可以这样做if (i % 8 == 0)
  • @epascarello 没有添加到 dom 树..Firefox 我可以看到颜色表,但 IE 什么也没显示。
  • 将单元格的 innerHTML 设置为空白。

标签: javascript internet-explorer appendchild


【解决方案1】:

正确的解决方案是var el = document.createElement('td'); el.onclick = el.onclick = new Function("clickHandler('"+color['R'][i]+"')"); 它适用于所有浏览器。

【讨论】:

    猜你喜欢
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 2020-09-05
    • 1970-01-01
    • 2020-10-31
    • 2013-08-10
    • 2017-01-07
    相关资源
    最近更新 更多