繁体   English   中英

如何在JavaScript中使用适当的变量注入

[英]How to use proper injection of variable in javascript

如何在javascript中正确使用产品ID注入。

  $(".vote_count").wrap("<a id='id' href='countvotes/{product_id}'</a>");

对于ES5 ,像这样

$(".vote_count").wrap('<a id="id" href="countvotes/' + encodeURIComponent(product_id) + '"></a>');

对于ES6,您可以使用string templates

$(".vote_count").wrap(`<a id="id" href="countvotes/${encodeURIComponent(product_id)}"></a>`);

如果您的问题是:“我在代码中有一个product_id变量,并希望将其放置在我有{product_id} ”,则有三个答案:( 如果您是在谈论id ,则答案基本上是相同的,适当的更改。)

  1. 字符串串联:

     $(".vote_count").wrap("<a id='id' href='countvotes/" + product_id + "'></a>"); 
  2. ES2015(aka ES6)模板字符串:

     $(".vote_count").wrap(`<a id='id' href='countvotes/${product_id}'></a>`); 
  3. 多个模板引擎中的任何一个。

通常,最好将它们与encodeURIComponent结合使用,因为您要输出一个URI,因此,如果product_id包含对URI具有特殊含义的内容(例如/ ),则需要对其进行转义。 所以:

$(".vote_count").wrap("<a id='id' href='countvotes/" + encodeURIComponent(product_id) + "'></a>");

要么

$(".vote_count").wrap(`<a id='id' href='countvotes/${encodeURIComponent(product_id)}'></a>`);

进一步说明:由于要输出HTML属性的内容,因此必须确保输出的内容是有效的HTML文本。 没有内置的功能,但是编写起来很简单:

var escapes = {
    '&': '&amp;',
    '<': '&lt;',
    '"': '&quot;'
};
function escapeHTML(str) {
    return str.replace(/[&<"]/g, function(ch) {
        return escapes[ch];
    };
}

(不需要转义> ,但是如果愿意,可以。)

使用该属性,我总是将我的属性括在双引号中(因为这些是我要转义的内容)。

所以:

$(".vote_count").wrap('<a id="id" href="countvotes/' + escapeHTML(encodeURIComponent(product_id)) + '"></a>");

$(".vote_count").wrap(`<a id="id" href="countvotes/${escapeHTML(encodeURIComponent(product_id))}"></a>`);

旁注:您缺少<a标签上的结尾> 上面已经解决了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM