什么是HTML重写的好方法? [英] What's a good alternative to HTML rewriting?

查看:68
本文介绍了什么是HTML重写的好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此文档片段:

<div id="test">
    <h1>An article about John</h1>
    <p>The frist paragraph is about John.</p>
    <p>The second paragraph contains a <a href="#">link to John's CV</a>.</p>
    <div class="comments">
        <h2>Comments to John's article</h2>
        <ul>
            <li>Some user asks John a question.</li>
            <li>John responds.</li>
        </ul>
    </div>
</div>

我想用字符串Peter替换字符串John的每一个匹配项。这个可以通过HTML重写来完成:

I would like to replace every occurrence of the string "John" with the string "Peter". This could be done via HTML rewriting:

$('#test').html(function(i, v) {
    return v.replace(/John/g, 'Peter');    
});

工作演示: http://jsfiddle.net/v2yp5/

上面的jQuery代码看起来很简单直接,但这是欺骗,因为它是一个糟糕的解决方案。 HTML重写会重新创建#test DIV中的所有DOM节点。随后,不会以编程方式(例如onevent处理程序)或用户(输入的表单字段)对该DOM子树所做的更改保留。

The above jQuery code looks simple and straight-forward, but this is deceiving because it is a lousy solution. HTML rewriting recreates all the DOM nodes inside the #test DIV. Subsequently, changes made on that DOM subtree programmatically (for instance "onevent" handlers), or by the user (entered form fields) are not preserved.

那么执行此任务的适当方法是什么?

So what would be an appropriate way to perform this task?

推荐答案

您希望遍历所有子节点并仅替换文本节点。否则,您可以匹配HTML,属性或序列化的任何其他内容。替换文本时,您只想使用文本节点,而不是整个HTML序列化。

You want to loop through all child nodes and only replace the text nodes. Otherwise, you may match HTML, attributes or anything else that is serialised. When replacing text, you want to work with the text nodes only, not the entire HTML serialised.

我认为你已经知道了这一点:)

I think you already know that though :)

Bobince有一个伟大的作品用于执行此操作的JavaScript

Bobince has a great piece of JavaScript for doing that.

这篇关于什么是HTML重写的好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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