重构 HTML 生成 JavaScript

发布于 2024-07-08 06:16:45 字数 1441 浏览 8 评论 0原文

不幸的是,在我的项目中,我们在 JavaScript 中生成了很多 HTML 代码,如下所示:

var html = new StringBuffer();
html.append("<td class=\"gr-my-deals\"><a href=\"").append(deal.url).append("\" target=\"_blank\">").append(deal.description).append("</a></td>");

我对此有 2 个具体的抱怨:

  1. 在 HTML 字符串中使用转义双引号 (\”)。 应将它们替换为单引号 (') 以提高可读性。
  2. 使用 .append() 而不是 JavaScript 字符串连接运算符“+”

应用这两个建议,会生成以下等效的代码行,我认为该代码行更具可读性:

var html = "<td class=’gr-my-deals’><a href=’" + deal.url + "’ target=’_blank’>" + deal.description + "</a></td>";

我现在正在寻找一种自动将第一行代码转换为第二行。 到目前为止,我所想到的就是对所有 Javascript 代码运行以下查找和替换:

Find:    ).append(  
Replace: +

这会将上面显示的代码行转换为:

html.append("<td class=\"gr-my-deals\"><a href=\"" + deal.url + "\" target=\"_blank\">" + deal.description + "</a></td>)";

这应该安全地删除除第一个“append()”语句之外的所有语句。 不幸的是,我想不出任何安全的方法来自动将转义的双引号转换为单引号。 请记住,我不能简单地进行查找/替换,因为在某些情况下您实际上确实需要使用转义双引号。 通常,这是当您生成包含嵌套 JS 的 HTML,并且 JS 包含字符串参数时,例如

function makeLink(stringParam) {

  var sb = new StringBuffer();
  sb.append("<a href=\"JavaScript:myFunc('" + stringParam + "');\">");
}

我的问题(最后)是:

  • 是否有更好的方法可以安全地将对 'append()' 的调用替换为 '+'
  • 有什么方法可以安全地用单引号替换转义的双引号,正则表达式吗?

干杯, 大学教师

Unfortunately on my project, we generate a lot of the HTML code in JavaScript like this:

var html = new StringBuffer();
html.append("<td class=\"gr-my-deals\"><a href=\"").append(deal.url).append("\" target=\"_blank\">").append(deal.description).append("</a></td>");

I have 2 specific complaints about this:

  1. The use of escaped double quotes (\”) within the HTML string. These should be replaced by single quotes (‘) to improve readability.
  2. The use of .append() instead of the JavaScript string concatentation operator “+”

Applying both of these suggestions, produces the following equivalent line of code, which I consider to be much more readable:

var html = "<td class=’gr-my-deals’><a href=’" + deal.url + "’ target=’_blank’>" + deal.description + "</a></td>";

I'm now looking for a way to automatically transform the first line of code into the second. All I've come up with so far is to run the following find and replace over all our Javascript code:

Find:    ).append(  
Replace: +

This will convert the line of code shown above to:

html.append("<td class=\"gr-my-deals\"><a href=\"" + deal.url + "\" target=\"_blank\">" + deal.description + "</a></td>)";

This should safely remove all but the first 'append()' statement. Unfortunately, I can't think of any safe way to automatically convert the escaped double-quotes to single quotes. Bear in mind that I can't simply do a find/replace because in some cases you actually do need to use escaped double-quotes. Typically, this is when you're generating HTML that includes nested JS, and that JS contains string parameters, e.g.

function makeLink(stringParam) {

  var sb = new StringBuffer();
  sb.append("<a href=\"JavaScript:myFunc('" + stringParam + "');\">");
}

My questions (finally) are:

  • Is there a better way to safely replace the calls to 'append()' with '+'
  • Is there any way to safely replace the escaped double quotes with single quotes, regex?

Cheers,
Don

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

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

发布评论

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

评论(5

云朵有点甜 2024-07-15 06:16:45

考虑切换到 JavaScript 模板处理器。 它们通常相当轻量,并且可以显着提高代码的清晰度......以及性能,如果您有大量的重用并选择预编译模板的话。

Consider switching to a JavaScript template processor. They're generally fairly light-weight, and can dramatically improve the clarity of your code... as well as the performance, if you have a lot of re-use and choose one that precompiles templates.

许久 2024-07-15 06:16:45

这是一个 stringFormat 函数,可以帮助消除串联和丑陋的替换值。

function stringFormat( str ) {

    for( i = 0; i < arguments.length; i++ ) {
        var r = new RegExp( '\\{' + ( i ) + '\\}','gm' );

        str = str.replace( r, arguments[ i + 1 ] );    
    }
    return str;
}

像这样使用它:

var htmlMask = "<td class=’gr-my-deals’><a href=’{0}’ target=’_blank’>{1}</a></td>";

var x = stringFormat( htmlMask, deal.Url, deal.description ); 

Here is a stringFormat function that helps eliminate concatenation and ugly replacment values.

function stringFormat( str ) {

    for( i = 0; i < arguments.length; i++ ) {
        var r = new RegExp( '\\{' + ( i ) + '\\}','gm' );

        str = str.replace( r, arguments[ i + 1 ] );    
    }
    return str;
}

Use it like this:

var htmlMask = "<td class=’gr-my-deals’><a href=’{0}’ target=’_blank’>{1}</a></td>";

var x = stringFormat( htmlMask, deal.Url, deal.description ); 
递刀给你 2024-07-15 06:16:45

正如 Shog9 所暗示的,有几个很好的 JavaScript 模板引擎。 下面是如何使用我的 jQuery 简单模板 的示例:

var tmpl, vals, html;

tmpl  = '<td class="gr-my-deals">';
tmpl += '<a href="#{href}">#{text}</a>';
tmpl += '</td>';

vals  = {
    href : 'http://example.com/example',
    text : 'Click me!'
};

html  = $.tmpl(tmpl, vals);

As Shog9 implies, there are several good JavaScript templating engines out there. Here's an example of how you would use mine, jQuery Simple Templates:

var tmpl, vals, html;

tmpl  = '<td class="gr-my-deals">';
tmpl += '<a href="#{href}">#{text}</a>';
tmpl += '</td>';

vals  = {
    href : 'http://example.com/example',
    text : 'Click me!'
};

html  = $.tmpl(tmpl, vals);
泪痕残 2024-07-15 06:16:45

在 JavaScript 中应该使用 StringBuffer() 而不是字符串连接,这是有充分理由的。 StringBuffer() 及其append() 方法使用Array 和Array 的join() 将字符串组合在一起。 如果您想要连接大量的部分字符串,那么这是一种更快的方法。

There is a good reason why you should be using the StringBuffer() instead of string concatenation in JavaScript. The StringBuffer() and its append() method use Array and Array's join() to bring the string together. If you have a significant number of partial strings you want to join, this is known to be a faster method of doing it.

睡美人的小仙女 2024-07-15 06:16:45

模板化? 模板很糟糕! 这是我编写代码的方式:

TD({ "class" : "gr-my-deals" },
   A({ href : deal.url,
       target : "_blank"},
     deal.description ))

我使用一个名为 DOmination 的 20 行库,我会将其发送给任何询问的人,以支持此类代码。

优点是多方面的,但其中一些最明显的是:

  • 清晰、直观的代码
  • 易于学习和编写
  • 紧凑的代码(没有关闭标签,只有关闭括号)
  • 等很好地理解
  • 能够被 JavaScript 感知的编辑器、压缩器 一些特定于浏览器的问题(例如 IE 上的 rowSpan 和 rowspan 之间的差异)
  • 与 CSS 集成得很好

(顺便说一句,您的示例突出了 DOmination 的唯一缺点:任何同时也是 JavaScript 保留字的 HTML 属性,class 在这种情况下,必须被引用,以免发生不好的事情。)

Templating? Templating sucks! Here's the way I would write your code:

TD({ "class" : "gr-my-deals" },
   A({ href : deal.url,
       target : "_blank"},
     deal.description ))

I use a 20-line library called DOMination, which I will send to anyone who asks, to support such code.

The advantages are manifold but some of the most obvious are:

  • legible, intuitive code
  • easy to learn and to write
  • compact code (no close-tags, just close-parentheses)
  • well-understood by JavaScript-aware editors, minifiers, and so on
  • resolves some browser-specific issues (like the difference between rowSpan and rowspan on IE)
  • integrates well with CSS

(Your example, BTW, highlights the only disadvantage of DOMination: any HTML attributes that are also JavaScript reserved words, class in this case, have to be quoted, lest bad things happen.)

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