How to use variable in string in jQuery

后端 未结 7 2016
陌清茗
陌清茗 2020-12-08 23:28

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.


    

        
相关标签:
7条回答
  • 2020-12-08 23:42

    Concatenating can be done with + as follows.

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

    Reference:

    • https://developer.mozilla.org/en/JavaScript/Reference/Operators/String_Operators
    0 讨论(0)
  • 2020-12-08 23:42

    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

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

    $(".html").html(`<div class="new" id="${id}">jitender</div>`)
    
    0 讨论(0)
  • 2020-12-08 23:48

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

    $("a").click(function() {
        var id= $(".id").html();
        // create new element
        $('<div>', { 
            class:'new', 
            id: id, 
            text: 'jitend'
        }).appendTo('.html'); // and append it
    });
    
    0 讨论(0)
  • 2020-12-08 23:50

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

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

    here id is variable

    0 讨论(0)
  • 2020-12-08 23:51

    Try this

    $(".html").html("<div class='new' id='"+id+"'>jitender</div>")
    
    0 讨论(0)
提交回复
热议问题