[英]Better way to generate HTML using coffeescript / jQuery than using strings?
这是我第一次完成“回答您自己的问题”一文,所以我希望我能做到这一点。
我的问题是,“有比使用标记字符串更好的方法来用jQuery生成HTML吗?” 我希望能够生成嵌套的html而不创建像这样的长乱字符串
$("<form action='#{submitURL}' class='my_form'><input type='text'>...</form>")
而是使用嵌套函数调用。 我希望HTML生成代码看起来像这样:
$.el.form
id: "enrollment_form"
class: "myFormClass"
action: "/do_form", method: "post"
[
$.el.input
type: "text"
name: "last_name"
placeholder: "Last name"
$.el.input
type: "text"
name: "first_name"
placeholder: "First name"
$.el.div
class: "action"
$.el.input
type: "submit"
]
我创建了一个简单的jQuery扩展来解决这个问题(我创建了一个“ el”命名空间以避免冲突)。 用法如下:
$.el.<html element name>(htmlAttributes, content)
...其中内容可以是对$ .el。的另一个调用,也可以是此类调用的数组
因此创建:
<u><i>This is underlined italicized</i></u>
你会这样写:
$.el.u {},
$.el.i {}, "This is underlined italicized"
并创建此:
<ul class="my_class">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
你会这样写:
$.el.ul {class: "my_class"},
[
$.el.li {}, "First item"
$.el.li {}, "Second item"
$.el.li {}, "Third item"
]
这简化了HTML的生成,并摆脱了一堆凌乱的字符串插值和连接。
jsFiddle在这里: https ://jsfiddle.net/jplato/tv1Lqa52/8/,并且我欢迎任何关于如何改进它的反馈。
如果您要创建非常大的DOM元素,则绝对建议使用javascript模板(我最喜欢的是Handlebars )
如果要创建一小段DOM,则有一种优雅的方法。 即将所有属性放入{}。
例如:$(“ tagName”,{attr1:value1,attr2,value2 ....});
例如,如果我们要创建一个简单的表单
<form action="google.com">
<input type="text" value="hello" class="red-border">
<button type="submit">click me</button>
</form>
使用此代码比将所有内容放入一个巨大的字符串中更具可读性,并且更容易将事件绑定到每个元素
var form = $("<form/>",{
action: "google.com"
});
var input = $("<input>",{
type:"text",
value:"hello",
class:"red-border"
}).appendTo(form);
var button = $("<button/>",{
text:"click me",
type:"submit",
style:"font-size:20px"
}).appendTo(form);
button.click(function(){
alert("clicked");
})
form.appendTo($("#container"));
我认为茶杯是最好的解决方案。 您的第一个示例可能类似于(未测试):
render ->
form '.my_form'
action: submitURL
->
input type: 'text', ->
...
还有第二个示例(同样,未测试):
render ->
form '#enrollment_form.myFormClass',
action: '/do_form'
method: 'post'
->
input type: 'text', name: 'last_name', placeholder: 'Last name'
input type: 'text', name: 'first_name', placeholder: 'First name'
div '.action', ->
input type: 'submit'
这看起来与您的示例非常接近,甚至还不算干净。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.