JavaScript: can an input type=checkbox use appendChild in IE8 or not?
According to http://msdn.microsoft.com/en-us/library/ms535934(v=VS.85).aspx and http://msdn.microsoft.com/en-us/library/ms535262(v=VS.85).aspx , I should be able to do the following to create a new checkbox:
var answer = document.createElement('input');
answer.setAttribute('type', 'checkbox');
answer.setAttribute('id', 'answer');
answer.setAttribute('value', 'a');
answer.appendChild(document.createTextNode('test'));
This works in Firefox and Chrome, but in IE 8, the last function call produces the following error message:
Error: Unexpected call to method or property access.
I have tried bypassing this by using the innerText attribute instead, but this approach receives the same error message.
Am I doing something wrong? If so, what? If not, how can I circumvent 开发者_JS百科what appears to be nonsense?
I don't think you want to add a text node to your checkbox. Instead I would use a label object with two child nodes: the checkbox input and a text node:
var answer = document.createElement('input');
answer.setAttribute('type', 'checkbox');
answer.setAttribute('id', 'answer');
answer.setAttribute('value', 'a');
var answerLabel = document.createElement('label');
answerLabel.setAttribute('for','answer'); // this corresponds to the checkbox id
answerLabel.appendChild(answer);
answerLabel.appendChild(document.createTextNode(' test'));
document.body.appendChild(answerLabel);
You can use:
var label = document.createElement('label');
label.answer;
label.appendChild(document.createTextNode('test'));
精彩评论