生成具有动态内容的字符串

时间:2019-09-18 14:47:55

标签: javascript html

我有一个像下面这样的字符串,

var markup = "<p class='error-info-popup-link' onclick='processData.getErrorInfoPopup("+helper.qaConstants[item.errors[i]]+", "+item.source+", "+ seqNo +")'> Info </p>"

上面的字符串输出是:-

<p class="error-info-popup-link" onclick="processData.getErrorInfoPopup(Numeric Mismatch, 1, 2)"> Info </p> 

我想要下面的输出:-

<p class="error-info-popup-link" onclick="processData.getErrorInfoPopup('Numeric Mismatch', 1, 2)"> Info </p>

我该怎么办?

2 个答案:

答案 0 :(得分:1)

只需添加转义引号即可:

var markup = "<p class='error-info-popup-link' onclick='processData.getErrorInfoPopup(\""+helper.qaConstants[item.errors[i]]+"\", "+item.source+", "+ seqNo +")'> Info </p>"

或使用模板:

var markup = `<p class='error-info-popup-link' onclick='processData.getErrorInfoPopup("${helper.qaConstants[item.errors[i]]}", ${item.source}, ${seqNo})'> Info </p>`

答案 1 :(得分:1)

我个人会说完全绕开该问题,并避免内联绑定。

var newP = document.createElement('p');

newP.classList.add('error-info-popup-link');
newP.innerText = ' Info ';
newP.addEventListener('click', function(){
  processData.getErrorInfoPopup(
    helper.qaConstants[item.errors[i]],
    item.source,
    seqNo
  );
});