我有一个可以用 javascript 和 Ajax 很好地填充的表,但现在我需要添加复选框,并让它们在以这种方式保存在数据库中时显示已选中(1 表示选中,0 表示未选中)。而不是写
var aChecked='';
aChecked += '<input type="checkbox" id="amS"'+(data.amS == 1 ? 'checked="checked"':'')+'/>';
对于每个复选框(大约有 24 个),我尝试使用修改后的函数,用于查看是否选中了表中未列出的其他复选框。其功能是:
function Checked(){
this.update();
}
位于我的 $.ajax 之上,这是我的 success(function(data) 部分。
Checked.prototype.list = ['am','fol','tich','book','neb','ster','byte','ing'];
Checked.prototype.update = function(){
for( var i = 0 ; i < this.list.length ; i++ ){
var check = this.list[i];
this[ check + 'S' ] += '<input type="checkbox" id="'+this[ check + 'S' ]+'"'+(data.this[ check + 'S' ] == 1 ? 'checked="checked"':'')+'/>';//$("#" + check ).is(":checked") ? 1 : 0;
}// end of for loop
}
var checks = new Checked();
然后我可以像这样在我的附加语句中引用它
<td>'+checks.amS+'</td>
问题是当我尝试运行它时遇到此错误:
TypeError: data.this is undefined
我不确定我需要如何编写它才能使其正常工作,而不必写得很长并且违反 DRY 原则。我已经尝试过了
data.(this[ check + 'S' ])
和
data.[this[ check + 'S' ]]
两者都会引发语法错误。有人知道我怎样才能做到这一点吗?谢谢
最佳答案
改变
this[ check + 'S' ] += '<input type="checkbox" ... >'
// this[ check + 'S' ] = this[ check + 'S' ] + '<input type="checkbox" ... >'
// this[ check + 'S' ] = undefined + '<input type="checkbox" ... >'
到
this[ check + 'S' ] = '<input type="checkbox" ... >'
请检查您的代码
this[ check + 'S' ] =
'<input type="checkbox" id="'+this[ check + 'S' ]+'"' // this[ check + 'S' ] is undefined
+(data.this[ check + 'S' ] == 1 ? 'checked="checked"':'')+'/>'; // this[ check + 'S' ] is undefined
//$("#" + check ).is(":checked") ? 1 : 0;
至
this[ check + 'S' ] =
'<input type="checkbox" id="'+check + 'S'+'"' // modified
+(data[ check + 'S' ] == 1 ? 'checked="checked"':'')+'/>'; // modified
//$("#" + check ).is(":checked") ? 1 : 0;
在这种情况下,“this”意味着对您的更新函数进行“var 检查”
“data[this]”确实是错误的访问,
为什么这意味着对象(实例)而不是字符串(对象的键)
关于javascript - 尝试使用函数通过 Javascript 动态填充 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26063070/