我正在使用jQuery动态创建一些复选框元素,并将它们附加到像这样的节点
var topics = ['All','Cat1','Cat2'];
var topicContainer = $('ul#someElementId');
$.each( topics, function( iteration, item )
{
topicContainer.append(
$(document.createElement("li"))
.append(
$(document.createElement("input")).attr({
id: 'topicFilter-' + item
,name: item
,value: item
,type: 'checkbox'
,checked:true
})
.click( function( event )
{
var cbox = $(this)[0];
alert( cbox.value );
} )
)
.append(
$(document.createElement('label')).attr({
'for': 'topicFilter' + '-' + item
})
.text( item )
)
)
} );
我遇到的问题是双重的(仅在IE中存在)
alert( cbox.value );
时,每次输出都为“on”。我认为这里的核心问题是我需要一种更好的方法来设置复选框的默认选中状态,并设置其默认的“值”属性。但我还没有找到另一种方式。
注意:所有这些代码在Firefox和Chrome中都能正常运行。
这是使用IE 7.0.5730.11进行的jQuery 1.3.1测试
答案 0 :(得分:14)
Internet Explorer不希望您更改不属于DOM的输入的选中值。尝试在附加项目后设置选中的值,看看是否有效。
答案 1 :(得分:2)
我重复使用了一些代码,并且根据
遇到了类似的问题Why does order of defining attributes for a dynamically created checkbox in jquery affect its value?
我发现解决方案只是简单地移动属性声明
type: 'checkbox',
到开头即:
$(document.createElement("input")).attr({
type: 'checkbox',
这个问题在所有浏览器中都出现了,所以我不认为它是一个IE问题,而是一个jquery“东西”。对我来说,当我设置值(之前或之后)追加时并不重要。不同之处在于我声明输入类型的时间/地点。
答案 2 :(得分:1)
选中复选框的“已选中”属性的状态不为true,其状态为“已检查”字符串。我通常使用jQuery将元素添加到DOM:
var el = $('<input type="checkbox" id="topicFilter-' + '"'
+ ' checked="checked" />');
$(topicContainer).append(el);
无论如何,IMO更加清晰,读起来像HTML。如果它在IE中也不起作用我会被诅咒,我这么多年来一直这样做。