jQuery 动态创建 table/tr/td 或 etc 并附加属性 [英] jQuery dynamically create table/tr/td or etc and append attributes
问题描述
在一个例子中,我有这个结构(小例子):
In an example I am having this structure (small example):
<table id=example>
<tr class="blah test example"><td>Test1</td><td><a href="url">LINK</a>Test11</td></tr>
<tr class="blah test example"><td>Test2</td><td><a href="url">LINK</a>Test22</td></tr>
<tr class="blah test example"><td>Test3</td><td><a href="url">LINK</a>Test33</td></tr>
</table>
在 jQuery 中,我会像这样动态创建它:
In jQuery I would create it dynamically like:
var test = "<table id=" + someIDVar + ">"
+ "<tr class=" + classOneVar
+ classTwoVar + classThreeVar + ">"....
等等等等......(还有很多其他的东西要写).在我只是附加它之后:
and etc etc... (lots of other stuff to write). After I would just append it:
$(".somePlaceInHtml").append(test);
那么有没有其他方法可以用 jQuery 动态地编写这样的结构?这对我来说是一个问题,因为我有一个很大的结构,不像我在示例中展示的那么小.主要原因是我希望自己和其他维护此代码的开发人员具有更好的可读性.
So is there any other way to write such a structure dynamically with jQuery? This is a problem for me because I am having a big structure, not as small as I showed in the example. The main reason is I want to get better readability for myself and other developers who will maintain this code.
推荐答案
你能用你的字符串制作一个模板"吗?如果是,则将其存储在常量"变量中(例如在全局范围内定义),其中包含实际变量的占位符,例如 {0}
、{1}
等,就像在 C# 的 string.format()
方法中使用它一样.
Can you make a "template" out of your string? If yes, then store it in a "constant" variable (e.g. defined in global scope), containing placeholders for actual variables, like {0}
, {1}
etc, as you would use it in C#'s string.format()
method.
所以,你会有这样的代码:
So, you would have code like this:
var rowTemplate = "<tr><td>{0}</td><td>SomePredefinedText {1}</td></tr>";
var alternateRowTemplate = "<tr><td class='a'>{0}</td><td>SomewhatDifferent {1}</td></tr>";
...... somewhere deep in your code
$("#someElement").append(
rowTemplate.format("myvalue1", "myvalue2")
).append(
alternateRowTemplate.format("myvalue3", "myvalue4")
);
然后您将按照此答案使用 string.format 实现:等效于 jQuery 中的 String.format
You would then use the string.format implementation as per this answer: Equivalent of String.format in jQuery
这篇关于jQuery 动态创建 table/tr/td 或 etc 并附加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!