简体   繁体   中英

Javascript generate many DOM elements with onclick attribute

I have the following script:

var div = document.getElementById("ShowAndHide");
var colbutton = document.createElement("a");
var linkText = document.createTextNode("Show/Hide column");
colbutton.appendChild(linkText);
colbutton.setAttribute("href", "javascript:void(0)");
jQuery.each(data.aoColumns, function(i, value){
    colbutton.onclick = function(){
        fnShowHide(i);
    }
div.appendChild(colbutton);
});

function fnShowHide( iCol ){
var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
oTable.fnSetColumnVis( iCol, bVis ? false : true );
}

Basically what I need is to create a number of DOM elements with sightly different attributes. I haven't found anything helpful so I decide to ask here. Thanks!

I've seen that you're already use jQuery. So here is a jQuery solution:

var $div = $("#ShowAndHide");
var $colbutton = $("<a href='javascript:void(0)'>Show/Hide column</a>");

$.each(data.aoColumns, function(i) {
    $colbutton.clone()
        .on('click', fnShowHide.bind(window, i))
        .appendTo($div);
});

function fnShowHide( iCol ){
    var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
    oTable.fnSetColumnVis( iCol, bVis ? false : true );
}

Here is a working jsFiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM