window.onload=function(){
var container = document.getElementById('container'),
template = '<li>\
<input type="checkbox">\
</li>\
<li>\
<input type="checkbox">\
</li>\
<li>\
<input type="checkbox">\
</li>';
container.onchange = function(e) {
var event = e || window.event,
target = event.srcElement || event.target;
if( target.checked && target.parentNode.getElementsByTagName('ul').length === 0 ) {
var ul = do开发者_运维问答cument.createElement('ul');
ul.innerHTML = template;
target.parentNode.appendChild(ul);
} else {
var ul = target.parentNode.getElementsByTagName('ul')[0];
target.parentNode.removeChild(ul);
}
};
}
<ul id="container">
<li>
<input type="checkbox">
</li>
<li>
<input type="checkbox">
</li>
<li>
how to assign unique id to every checkbox in the above code.................
<input type="checkbox">
</li>
</ul>
Instead of hard-coding your checkbox markup in window.onload
, I'd add a createCheckbox
function to handle creating unique IDs for you.
Here's an example:
var gCheckboxID = 0;
function createCheckbox()
{
return '<input type="checkbox" id="Prefix' + String(gCheckboxID++) + '" />';
}
Then, each time you call createCheckbox
, you'll be given markup for a new element with a unique ID.
Here you go:
window.onload = function() {
var container = document.getElementById('container');
container.onchange = function(e) {
var event = e || window.event,
target = event.srcElement || event.target,
ul, str = '', i;
if ( target.checked && target.parentNode.getElementsByTagName('ul').length === 0 ) {
ul = document.createElement('ul');
for ( i = 0; i < 3; i++ ) {
str += '<li><input type="checkbox" id="cb_' + +(new Date) + i + '"></li>';
}
ul.innerHTML = str;
target.parentNode.appendChild(ul);
} else {
ul = target.parentNode.getElementsByTagName('ul')[0];
target.parentNode.removeChild(ul);
}
};
};
So instead of using a static template, I create the HTML string in a loop. The ID is based on the result of new Date
(which returns a time-stamp) and the iterator i
. For instance the ID values might be:
- cb_13065045104750
- cb_13065045104751
- cb_13065045104752
Live demo: http://jsfiddle.net/simevidas/psmR5/
精彩评论