JQuery:通过 DOM 操作插入大量 html - 可维护性?

发布于 2024-10-26 00:09:25 字数 1717 浏览 4 评论 0 原文

我发现了关于使用 jquery 插入 dom 元素的良好实践的好帖子,例如 this这个这个

当你只需要插入一些元素时就可以了,但在我看来从可维护性的角度来看,这些选项非常糟糕(代码重复两次,因此如果需要任何更改,则需要发生两次,然后很容易出错),

这(只是一小部分)我已经有

<script type="text/javascript">
var phnFragment = "<tr><td align=\"right\">Telephone:</td><td colspan=\"2\"><select name=\"select\" size=\"1\"style=\"width: 100px;\"><option>-- Choose --</option><option>Home</option><option>Mobile</option><option>Work</option></select><input type=\"text\" size=\"20px\" /></td></tr>";
    $(document).ready(function() {
    $('#addmorephones').click(function() {
                $("#phones").append(phnFragment);
            });
    });
</script>
....
....
<tr id="phones">
        <td align="right">Telephone:</td>
        <td colspan="2"><select name="select" size="1"
            style="width: 100px;">
            <option>-- Choose --</option>
            <option>Home</option>
            <option>Mobile</option>
            <option>Work</option>
        </select><input type="text" size="20px" /> <a href="javascript:void(0);" id="addmorephones">[+]</a>
        </td>
    </tr>

没有更好的方法来完成这个?有没有办法告诉jquery复制部分dom树并将其作为片段插入?

很想学习替代方案

I've found good posts on good practices inserting dom elements using jquery like this, this and this

It's ok when you just need to insert a few elements, but it seems to me that these option are very bad from the point of view of maintainability (Code is repeated twice, thus if any change is needed it needs to happen twice then it becomes very prone to error ),

This is (just a small part) what I've got

<script type="text/javascript">
var phnFragment = "<tr><td align=\"right\">Telephone:</td><td colspan=\"2\"><select name=\"select\" size=\"1\"style=\"width: 100px;\"><option>-- Choose --</option><option>Home</option><option>Mobile</option><option>Work</option></select><input type=\"text\" size=\"20px\" /></td></tr>";
    $(document).ready(function() {
    $('#addmorephones').click(function() {
                $("#phones").append(phnFragment);
            });
    });
</script>
....
....
<tr id="phones">
        <td align="right">Telephone:</td>
        <td colspan="2"><select name="select" size="1"
            style="width: 100px;">
            <option>-- Choose --</option>
            <option>Home</option>
            <option>Mobile</option>
            <option>Work</option>
        </select><input type="text" size="20px" /> <a href="javascript:void(0);" id="addmorephones">[+]</a>
        </td>
    </tr>

Is there a better way to accomplish this? Is there a way to tell jquery to copy part of the dom tree and use it as fragment to insert?

Would love to learn alternatives

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦中的蝴蝶 2024-11-02 00:09:25

有没有办法告诉jquery复制部分dom树并将其作为片段插入?

是:克隆。 (你甚至不需要 jQuery;cloneNode 是 DOM API 的一部分。)如果您克隆的内容中有任何 id 值,则需要当然,迭代结果会改变它们,因为 id 必须是唯一的。但它非常适合表格行等。

在页面加载时,您可以抓取一个真实的模型,克隆它(不将其附加到文档),清除其中不需要的任何内容,然后继续克隆该模型。帮助您的 JavaScript 在某种程度上与您的标记分离。

示例:

HTML:

<table>
  <tbody>
    <tr><td>I'm a row in the table</td></tr>
  </tbody>
</table>

JavaScript:

jQuery(function($) {
  var counter = 10,
      rowModel;

  // Get the row model, clone it, remove the
  // content we'll replace anyway.
  rowModel = $("tr:first").clone();
  rowModel.find("td:first").empty();

  // Do our first tick
  tick();

  // Use the model to append to the table
  function tick() {
    var clone = rowModel.clone();

    clone.find("td:first").html("Added at " + new Date());
    $("tbody:first").append(clone);

    // Again?
    if (--counter > 0) {
      setTimeout(tick, 500);
    }
  }

});

Live copy

显然,这是一个快速而肮脏的方法,但你明白了。如果您使用 data-xyz 属性(HTML5 中允许)、nameclass 等,您也可以避免绑定代码与你的结构密切相关。

Is there a way to tell jquery to copy part of the dom tree and use it as fragment to insert?

Yes: clone. (You don't even really need jQuery for it; cloneNode is part of the DOM API.) If you have any id values in what you clone, you'll need to iterate over the result changing them, of course, since ids have to be unique. But it's perfect for things like table rows and the like.

On page load, you can grab one of the real ones, clone it (without attaching it to the document), cleanse it of anything you don't need, and then just keep cloning that model. Helps keep your JavaScript somewhat decoupled from your markup.

Example:

HTML:

<table>
  <tbody>
    <tr><td>I'm a row in the table</td></tr>
  </tbody>
</table>

JavaScript:

jQuery(function($) {
  var counter = 10,
      rowModel;

  // Get the row model, clone it, remove the
  // content we'll replace anyway.
  rowModel = $("tr:first").clone();
  rowModel.find("td:first").empty();

  // Do our first tick
  tick();

  // Use the model to append to the table
  function tick() {
    var clone = rowModel.clone();

    clone.find("td:first").html("Added at " + new Date());
    $("tbody:first").append(clone);

    // Again?
    if (--counter > 0) {
      setTimeout(tick, 500);
    }
  }

});

Live copy

Obviously that's a quick-and-dirty, but you get the idea. If you use data-xyz attributes (allowed in HTML5), names, classes, etc., you can avoid tying your code too closely to your structure.

苹果你个爱泡泡 2024-11-02 00:09:25

在这种情况下,您可以在就绪事件期间抓取#phones的内容:

$(document).ready(function() {
    var phnFragment = $("#phones").html();

    $('#addmorephones').click(function() {
        $("#phones").append(phnFragment);
    });
});

如果您需要复制更复杂的信息(例如事件),您可以使用.clone() 方法

$(document).ready(function() {
    var $phnFragment = $("#phones").children().clone();

    $('#addmorephones').click(function() {
        $("#phones").append($phnFragment.clone());
    });
});

In this case, you could grab the contents of #phones during the ready event:

$(document).ready(function() {
    var phnFragment = $("#phones").html();

    $('#addmorephones').click(function() {
        $("#phones").append(phnFragment);
    });
});

If you need to copy more complex information (like events), you can use the .clone() method:

$(document).ready(function() {
    var $phnFragment = $("#phones").children().clone();

    $('#addmorephones').click(function() {
        $("#phones").append($phnFragment.clone());
    });
});
各空 2024-11-02 00:09:25

如果您有想要重用的现有标记,TJ 有一个很好的答案。您还可以使用 text/html 脚本类型将内容作为模板放入标记中,如下所示:

http://ejohn.org/blog/javascript-micro-template/

T.J. has a great answer if you've got existing markup you want to reuse. You can also use the text/html script type to put your content in markup as a template, as demonstrated here:

http://ejohn.org/blog/javascript-micro-templating/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文