将表单元素附加到表 [英] appending form elements to a table
问题描述
当前我正在执行以下操作:
Currently I am doing the following:
var row = "<tr>";
$("#addServiceForm input, #addServiceForm select").each(function(index){
row += "<td><input type='text' id='someId' name='someName' value='someValue'></td>";
});
var row "</tr>";
$('#someTable').append(row);
我的伪问题是行线变长. 我正在尝试以一种更具可读性的方式进行操作.以前的问题此处追加到表单时的元素部分,将行和输入追加到表怎么办?
my pseudo-issue is that row line gets long. I was trying to do it in a more readable fashion. A previous question Here helped with the element portion when appending to form, what about appending a row and input to a table?
$("#addServiceForm input, #addServiceForm select").each(function(index){
var element = $('<input>',{
id:idName,
name:idName,
val:thisVal
}).addClass('verify');
row += "<td class='verify'>"+element+"</td>";
});
$('#someTable').append(row);
不起作用.我最终得到:
does not work. I end up with:
<td>[OBJECT]</td>
根据您的回答,缩短的最佳方法是什么:
based on your answer, what is the best way to shorten:
var row = "<td><input type='text' id='someIdthatisLong' name='someNamethatisLong' value='someValuethatislong' class='verify' readonly='readonly'></td>";
推荐答案
如果要使用对象,则需要始终使用它们,而不是将它们与字符串混合.
If you're going to work with objects, you need to use them consistently, not mix them with strings.
var row = $("<tr>");
$("#addServiceForm input, #addServiceForm select").each(function(index){
var element = $('<input>',{
id:idName,
name:idName,
val:thisVal,
'class': 'verify'
});
row.append($("<td>").append(element));
});
$('#someTable').append(row);
但是,这不一定是最有效的方法.浏览器的HTML解析器非常高效,因此解析大型HTML字符串可能比用Javascript创建所有单个对象并将它们连接在一起要好.
However, this isn't necessarily the most efficient way to do it. The browser's HTML parser is extremely efficient, so parsing a big HTML string may be better than creating all the individual objects in Javascript and connecting them together.
这篇关于将表单元素附加到表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!