简体   繁体   English

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

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

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

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

For ES5 , like this 对于ES5 ,像这样

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

For ES6 you can use string templates 对于ES6,您可以使用string templates

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

If your question is: "I have a product_id variable and want to put it where I have {product_id} in this code," there are three answers: (The answers are essentially the same if you're talking about id instead, just make the appropriate changes.) 如果您的问题是:“我在代码中有一个product_id变量,并希望将其放置在我有{product_id} ”,则有三个答案:( 如果您是在谈论id ,则答案基本上是相同的,适当的更改。)

  1. String concatenation: 字符串串联:

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

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

Usually, best to combine those with encodeURIComponent , because you're outputting a URI, and so if product_id has things in it (like / ) that have special meaning in URIs, you need to escape them. 通常,最好将它们与encodeURIComponent结合使用,因为您要输出一个URI,因此,如果product_id包含对URI具有特殊含义的内容(例如/ ),则需要对其进行转义。 So: 所以:

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

or 要么

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

Taking that a bit further: Since you're outputting the content of an HTML attribute, you also have to ensure that what you're outputting is valid HTML text. 进一步说明:由于要输出HTML属性的内容,因此必须确保输出的内容是有效的HTML文本。 There's no built-in for that, but it's a trivial function to write: 没有内置的功能,但是编写起来很简单:

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

(There's no need to escape > , but you can if you like.) (不需要转义> ,但是如果愿意,可以。)

Using that, I always enclose my attributes in double quotes (since those are what I'm escaping). 使用该属性,我总是将我的属性括在双引号中(因为这些是我要转义的内容)。

So: 所以:

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

and

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

Side note: You were missing the closing > on the <a tag. 旁注:您缺少<a标签上的结尾> That's fixed in the above. 上面已经解决了。

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

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