我正在尝试使用 jquery 在 html 表中附加一些数据,它工作正常,但是当数据为空或空时,我必须将另一个div 附加到该 html 表中。
我像这样尝试
$("#table").append(data.d[i].one!=""?
"<td id='divs'>
<input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
<label for="+ data.d[i].one +"></label>
</td>":"<div></div>");
但它不起作用,请帮助我如何解决这个问题...
永远不明白为什么有人使用它
$("#table").append(data.d[i].one!=""?
"<td id='divs'>
<input id="+ data.d[i].one +" type=" + "checkbox" + " class=" + "cbCheck" + ">
<label for="+ data.d[i].one +"></label>
</td>":"<div></div>");
取而代之的是:
//class declaration
function YourTableCell(name, value) {
this.input = document.createElement('input');
this.input.value = value;
this.input.name = name;
this.label = document.createElement('label');
this.label.text = 'My Label';
this.container = document.createElement('td');
this.container.appendChild(this.input);
this.container.appendChild(this.label);
}
//application buisness logic
if(data.d[i].one != ''){
var cell = new YourTableCell(data.d[i].name, data.d[i].value);
$("#table").append(cell.container);
} else {
$("#table").append(document.createElement('div'));
}
使用这种方法,您可以在类中封装表单元构建,并使代码更具可读性和可重用性。另外,正如我现在看到的,您正在尝试将 td
附加到带有 id #table
的东西中,看起来它不正确,因为您应该在 tr
中附加td
。
此外,使用它,您可以获取对所有对象的引用,例如 input
s,并避免 $('input, select, textarea') 选择器。
你可以使用这样的东西,
var html = '<div></div>';
if(data.d[i].one) {
html = '<td id="divs"><input id="' + data.d[i].one + '" type="checkbox" class="cbCheck"><label for="' + data.d[i].one + '"></label></td>';
}
("#table").append(html);
您可以使用:
if( data.d ){
//Your code
}
这将检查data.d
是NULL
还是空字符串""
。
如果要签入每次迭代,请使用索引i
:
if( data.d[i] ){
//Your code
}
希望这有帮助。
看看 https://stackoverflow.com/a/5515349/4281779。