jQuery 如何在jquery中使用字符串中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11049275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:07:26  来源:igfitidea点击:

how to use variable in string in jquery

jqueryhtml

提问by Carlos

I want to use a variable in a string. I have tried to do it many times, but it is only getting the variable name.

我想在字符串中使用一个变量。我试过很多次,但它只得到变量名。

<head>
    <script type="text/javascript" src="jquery-1.7.2.js"></script>
    <script type="text/javascript">
       $(function(){
          $("a").click(function(){
           var id= $(".id").html();
           $('.html').html("<div class='new' id=+id+>jitender</div>")
             });
       });
    </script>
</head>
<body>
   <div class="wrap">
      <a href="#">Make Html</a>
      <div class="html"></div>
      <div class="id">first</div>
   </div>
</body>

回答by VisioN

Concatenating can be done with +as follows.

连接可以+按如下方式完成。

$('.html').html("<div class='new' id='" + id + "'>jitender</div>");

Reference:

参考:

回答by Kent Munthe Caspersen

You can also use template literals:

您还可以使用模板文字:

$('.html').html(`<div class='new' id=${id}>jitender</div>`)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

回答by Vivek

I felt this to be a more easy and efficient way. (use ``)

我觉得这是一种更简单有效的方法。(使用``)

$(".html").html(`<div class="new" id="${id}">jitender</div>`)

回答by Irfan DANISH

<script type="text/javascript">
$(function(){
$("a").click(function(){
    var id= $(".id").html();
    $('.html').html("<div class='new' id='"+id+"'>jitender</div>");
    })
})

回答by Ja?ck

The correct way of doing this is is by taking advantage of jQuery's HTML constructor to perform all the necessary escaping for you:

这样做的正确方法是利用 jQuery 的 HTML 构造函数为您执行所有必要的转义:

$("a").click(function() {
    var id= $(".id").html();
    // create new element
    $('<div>', { 
        class:'new', 
        id: id, 
        text: 'jitend'
    }).appendTo('.html'); // and append it
});

回答by Ja?ck

Try this

尝试这个

$(".html").html("<div class='new' id='"+id+"'>jitender</div>")

回答by wiese

Javascript does not support expanding variables inside double quotes. Close (and reopen) the quotes and use the + operator, as you already did.

Javascript 不支持在双引号内扩展变量。关闭(并重新打开)引号并使用 + 运算符,就像您已经做的那样。

"<div class='new' id='" + id + "'>"

"<div class='new' id='" + id + "'>"

here idis variable

id是变量