JQuery - 在 Javascript 中对 HTML 进行硬编码 - 有更好的方法来动态创建 dom 元素吗?
我有很多消息,以及我在 javascript 代码中硬编码的原始 HTML,例如:
var subjectId = $(subject).attr('subjectId');
var subjectName = $(subject).attr('subjectName');
var html = "<table id='invitations' class='invitations' width='100%'><tbody>";
$(subject).find('group').each( function() {
var groupId = $(this).attr('groupId');
var groupName = $(this).attr('groupName');
var ownerId = $(this).attr('ownerId');
var owner = findStudentNameById( subjectId, ownerId );
html += "<tr>" +
"<td width='55px'><img src='images/gplg.png' /></td>" +
"<td>" + subjectId + " <span class='subjectName'>" + subjectName + '</span> <br /> ' + groupId +
" - <span class='group'>" + groupName + "</span><br /> Created By " + owner + "</td>" +
"</tr>" +
"<tr>" +
"<td width='55px'></td>" +
"<td><img class='accept' src='images/accept.png' />" +
"<img class='decline' src='images/decline.png' /> " +
"</td>" +
"</tr>";
});
html += "</tbody></table>";
return html;
或 ...
$('#inviteform').submit( function (){
var invitesSent = false;
var html = '<h3>Invitations have been sent to the following people</h3><br /><ul>';
$('#inviteform').find('input:checkbox').each( function() {
if ( $(this).is(':checked')){
html += '<li>+ <a href="#">' + $(this).val() +'</a></li>';
invitesSent = true;
}
});
html += '</ul>';
if ( !invitesSent ){
html = '<h3>You did not select any invitees, no invitations have been sent.</h3>';
}
$('#content').hide().fadeOut(2000);
$('#content').html(html).slideDown("slow");
$('#slogan').html('Congratulations! Your group is now complete. ').fadeIn(2000);
return false;
});
这是因为我的页面有 2 个主要区域(即标题 div 和内容 div),我将其需要即时更改内容。 不幸的是,我无法将此内容分成不同的文件。
那么,为这些 div 创建文本和 DOM 元素是否有最佳实践,而不是硬编码这么多东西。
我正在寻找最优雅的解决方案,所以我没有那么多的硬编码。
谢谢
I have a lot of messages, and raw HTML that I hard code in my javascript code, such as:
var subjectId = $(subject).attr('subjectId');
var subjectName = $(subject).attr('subjectName');
var html = "<table id='invitations' class='invitations' width='100%'><tbody>";
$(subject).find('group').each( function() {
var groupId = $(this).attr('groupId');
var groupName = $(this).attr('groupName');
var ownerId = $(this).attr('ownerId');
var owner = findStudentNameById( subjectId, ownerId );
html += "<tr>" +
"<td width='55px'><img src='images/gplg.png' /></td>" +
"<td>" + subjectId + " <span class='subjectName'>" + subjectName + '</span> <br /> ' + groupId +
" - <span class='group'>" + groupName + "</span><br /> Created By " + owner + "</td>" +
"</tr>" +
"<tr>" +
"<td width='55px'></td>" +
"<td><img class='accept' src='images/accept.png' />" +
"<img class='decline' src='images/decline.png' /> " +
"</td>" +
"</tr>";
});
html += "</tbody></table>";
return html;
or ...
$('#inviteform').submit( function (){
var invitesSent = false;
var html = '<h3>Invitations have been sent to the following people</h3><br /><ul>';
$('#inviteform').find('input:checkbox').each( function() {
if ( $(this).is(':checked')){
html += '<li>+ <a href="#">' + $(this).val() +'</a></li>';
invitesSent = true;
}
});
html += '</ul>';
if ( !invitesSent ){
html = '<h3>You did not select any invitees, no invitations have been sent.</h3>';
}
$('#content').hide().fadeOut(2000);
$('#content').html(html).slideDown("slow");
$('#slogan').html('Congratulations! Your group is now complete. ').fadeIn(2000);
return false;
});
This is because I have a 2 main areas of the page (i.e title div, and content div), which I need to change the contents of on the fly. Unfortunately I cant separate this content into different files.
So, is there a best practices behind creating the text and DOM elements for these divs instead of hard coding so much stuff.
Im looking for the most elegant solution, so I don't have so much hard coding.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
它鼓励你对 HTML 字符串进行硬编码的方式是我最讨厌 jQuery 的地方之一。
我通常最终会使用标准的 Javascript:
document.createElement('TD')
如果您要创建大量相同类型的节点,最好/更快地缓存它们并使用
cloneNode (true)
创建新节点:我知道这并没有充分利用 jQuery,但我认为 jQuery 处理这个问题的方式并不优雅。
The way it encourages you to hardcode HTML strings is one of my pet hates with jQuery.
I generally just end up using the standard Javascript :
document.createElement('TD')
If you are creating a lot of nodes of the same type it's best/faster to cache them and use
cloneNode(true)
to create the new nodes:I understand this isn't makeing much use of jQuery but I think jQuery's way of handling this is inelegant.
您应该查看模板库。 jQuery 模板引擎
You should look at a templating library. jQuery templating engines
您可以使用 jQuery 的选择器来创建 DOM 元素。 例如,
将创建一个表元素,然后您可以在其上设置属性,然后附加到 DOM。
You can use jQuery's selector to create DOM elements. For example,
Will create a table element which you can then set attributes on and then append to the DOM.
一种替代方法是使用append()、addClass()、css()、attrib()和其他jQuery方法来构造DOM。 链接将使代码更加优雅。 这会很有效,特别是对于小型 DOM 树。
如果您需要更大的 DOM 树,那么最好使用 AJAX 方法从服务器获取它们。 您将需要调整您的代码才能传递动态生成的数据。
另外,您可以考虑重新设计 html 和 javascript 代码。 例如,您可以将 DOM 树放入 html 中并隐藏它(使用 CSS 或 javascript)。 然后您可以在添加动态生成的数据后显示它。 从关注点分离的角度来看,这要好得多。
One alternative is to use append(), addClass(), css(), attrib() and other jQuery methods to construct DOM. Chaining will make the code more elegant. This will work well, especially for small DOM trees.
If you need bigger DOM trees, then it would be better to use AJAX methods to fetch them from the server. You will need to adapt your code in order to pass the dynamically generated data.
Also, you may consider redesigning your html and javascript code. You may for example put the DOM tree in the html and hide it (using CSS or javascript). Then you could show it after you have added the dynamically generated data. This is much better from separation of concerns point of view.
尝试通过ajax获取html。
这将分离 javascript 和 html,打破依赖关系。
Try fetching the html via ajax.
This will separate the javascript and the html, breaking the dependencies.
使用Ajax来调用用户控件会更好。
这样您就可以在 html 用户控件中完成所有标记。
在我的愚见。
Using Ajax to call user controls would be better.
That way you can do all your markup in a html user control.
In my humble opinion.
在你的情况下,我会将消息与标记分开。 您可以在页面中有一个空的 html 脚手架
,然后使用 jQuery 填充它。 这样,您可以将所有用户消息重构为外部 .js 文件,从而极大地简化 i18n。
顺便说一句,我不推荐 JQuery 模板引擎。 它们要么强迫您使用非常尴尬的语法(如 jTemplates),要么限制您进行简单的元素克隆。 恕我直言,使用 .clone() 方法几乎总是更好。
In your case I'd separate the messages from the markup. You can have an empty html scaffold in your page like
and later populate it using jQuery. This way, you could refactor all your user messages to an external .js file which greatly eases i18n.
BTW I can't recommend JQuery Template Engines. Either they force you to use a really awkward syntax (like jTemplates), or they limit you to simple element cloning. IMHO you are almost always better off using the .clone() method.