var id = snapshot.val().id;
var content = snapshot.val().content;
var textObj = '<p class="task-item">\
<input type="checkbox" />\
<span class="ui-icon ui-icon-clock"></span>\
<span class="task-content">'+content+'</span>\
<span class="task-detail"> detail</span>\
</p>';
I want to add the id variable (a number) in the first line to the class attribute of the p tag in the third line. Can it be embedded directly?
ringa_lee2017-06-26 10:54:52
var id = snapshot.val().id;
var content = snapshot.val().content;
var textObj = '<p class="task-item'+id+'">\
<input type="checkbox" />\
<span class="ui-icon ui-icon-clock"></span>\
<span class="task-content">'+content+'</span>\
<span class="task-detail"> detail</span>\
</p>';
typecho2017-06-26 10:54:52
The essence of your question is how to change the spliced HTML template. The essence is to splice strings.
The stupidest method
var textObj1 = '<p class="task-item"';
var textObj2 = '>\
<input type="checkbox" />\
<span class="ui-icon ui-icon-clock"></span>\
<span class="task-content">'+content+'</span>\
<span class="task-detail"> detail</span>\
</p>';
textObj = textObj1 + id + textObj2
Or use ES6 string template directly, which is more in line with your variable nesting. But there will be compatibility issues.
var textObj = `<p class="task-item${id}">\
<input type="checkbox" />\
<span class="ui-icon ui-icon-clock"></span>\
<span class="task-content">'+content+'</span>\
<span class="task-detail"> detail</span>\
</p>`;
巴扎黑2017-06-26 10:54:52
Since you are actually concatenating strings with JS, you can directly use JS’s +
to concatenate the strings.
Now that you know how to splice content
, the same goes for splicing id
var id = snapshot.val().id;
var content = snapshot.val().content;
var textObj = '<p class="task-item' + id + '">\
<input type="checkbox" />\
<span class="ui-icon ui-icon-clock"></span>\
<span class="task-content">' + content + '</span>\
<span class="task-detail"> detail</span>\
</p>';
Of course, you can also use ES6 template strings, but there will be issues with browser compatibility, as follows: (Note that the entire textObj
starts with `
and ends with `
)
var id = snapshot.val().id;
var content = snapshot.val().content;
var textObj = `<p class="task-item${id}">\
<input type="checkbox" />\
<span class="ui-icon ui-icon-clock"></span>\
<span class="task-content">${content}</span>\
<span class="task-detail"> detail</span>\
</p>`;