如何使用Javascript在IE中创建选中的单选按钮?

如何使用Javascript在IE中创建选中的单选按钮?,javascript,html,Javascript,Html,我试图使用IE7中的以下代码创建一个选中的单选按钮。但它不起作用 var x = document.createElement("input"); x.type="radio"; x.checked=true; //I also tried setAttribute here which doesn't work either. var spn=document.createElement("span"); spn.appendChild(x); document.body.appendCh

我试图使用IE7中的以下代码创建一个选中的单选按钮。但它不起作用

var x = document.createElement("input");
x.type="radio";
x.checked=true; //I also tried setAttribute here which doesn't work either.

var spn=document.createElement("span");
spn.appendChild(x);

document.body.appendChild(spn);
我发现我可以将
x.checked=true
放在appendChild语句之后,使其工作。我还注意到,当我将“radio”改为“checkbox”时,可以在不改变语句顺序的情况下进行检查

我真的被这些事实弄糊涂了。我在上面的代码中是否有错误


解决方案:最后,我明白这是一个IE错误。将新单选按钮附加到其父按钮时,选中的属性将被清除。因此,我必须调用“x.checked=true;”作为最后一条语句。

这不是jQuery:您必须自己构建属性:

var x = document.createElement("input");
x.type = 'radio';
x.checked = true;
但如果是jQuery:

$(document).ready(function() {
    var x = $("<input type='radio' checked='checked' value='value'/>");
    $("body").append($("<span></span>").append(x));});
$(文档).ready(函数(){
变量x=$(“”);
$(“body”).append($(“”)。append(x));});

这是一件奇怪的IE事情……您需要使用innerHTML或IE的扩展createElement,因为“expando”属性在单选按钮上不能正常工作


这应该可以解决问题。

我认为罗布的答案是正确的,既然如此;您应该接受他的。
defaultChecked
不是我知道的任何(X)HTML版本中
input
元素的属性。不是,但我们不能说MSIE遵循给定的约定!
var input = document.createElement("input");
input.setAttribute("type", "radio");
input.setAttribute("checked", "checked");

var span = document.createElement("span");
span.appendChild(input);

document.body.appendChild(span);
var x = document.createElement("input");
x.setAttribute('defaultChecked', 'defaultChecked');
x.type="radio";


var spn=document.createElement("span");
spn.appendChild(x);

document.body.appendChild(spn);