什么时候可以在字符串中换行?

时间:2018-07-03 09:32:05

标签: javascript jquery syntax line-breaks

对新手问题很抱歉。我有这段代码,但我不喜欢它,它不是很可读。我对此是全新的,我找不到答案。我想将追加后的部分扩展到多行,但是正确的语法是什么?

'buildHtml': function(data) {
    $('.visibility-attributes').append('<div class="div-table-row js-table-row"><div class="div-table-cell js-div-table-cell">Bestand</div><div class="div-table-cell js-div-table-cell-bolt"><span class="tab-product-attribute-name">' + data.stock.stocklevel + '</span></div></div><div class="div-table-row js-table-row"><div class="div-table-cell js-div-table-cell">Bestellbar</div><div class="div-table-cell js-div-table-cell-bolt"><span class="tab-product-attribute-name">' + data.stock.orderable + '</span></div></div>');
},

2 个答案:

答案 0 :(得分:1)

我想你正在寻找这个

    var myHtmlString = "<div class='div-table-row js-table-row'>\
    <div class='div-table-cell js-div-table-cell'>\
    Bestand\
    </div>\
    <div class='div-table-cell js-div-table-cell-bolt'>\
    <span class='tab-product-attribute-name'>" + data.stock.stocklevel + "</span>\
    </div>\
    </div>\
<div class='div-table-row js-table-row'>\
    <div class='div-table-cell js-div-table-cell'>Bestellbar</div>\
    <div class='div-table-cell js-div-table-cell-bolt'>\
    <span class='tab-product-attribute-name'>" + data.stock.orderable + "</span>\
    </div>\
    </div>";

$('.visibility-attributes').append(myHtmlString )

只需在每个新行的末尾写一个反斜杠字符,即可将整个内容视为一个字符串。 (防止+和“”引起的头痛)

或者:

您可以在隐藏的div中(作为模板)编写结构

并在所需的html元素中填充值,然后将模板复制到输出div

$("#hiddenDiv").find(".tab-product-attribute-name").html(data.stock.stocklevel);
//blah
//blah
$('.visibility-attributes').append($("#hiddenDiv").html());

答案 1 :(得分:0)

请注意将单引号'替换为`

'buildHtml': function(data) {
    $('.visibility-attributes').append(`
    <div class="div-table-row js-table-row">
       <div class="div-table-cell js-div-table-cell">Bestand</div>
       <div class="div-table-cell js-div-table-cell-bolt">
         <span class="tab-product-attribute-name">${data.stock.stocklevel}</span>
       </div>
    </div>
    <div class="div-table-row js-table-row">
       <div class="div-table-cell js-div-table-cell">Bestellbar</div>
       <div class="div-table-cell js-div-table-cell-bolt">
         <span class="tab-product-attribute-name">${data.stock.orderable}</span>
       </div>
    </div>
 `);
},