jQuery动态创建table / tr / td等,并追加属性 [英] jQuery dynamically create table/tr/td or etc and append attributes

查看:115
本文介绍了jQuery动态创建table / tr / td等,并追加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个例子中我有这个结构(小例子):

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等,并追加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆