我只是想知道如何在 javascript 变量中添加 html 代码?例如,我想在其中一个消息行中使用 HTML 代码(<a href="/example.html">
链接代码段):
var messages = [
"Please wait while we handle your request...",
"This is taking longer than usual to process - please wait...",
"We seem to be having trouble - please click here to contact support"
];
$.each(messages, function(index, message) {
setTimeout(function() {
$('#wrapper').append(
$('<p />', {text : message})
)
}, index * 1500); // 1.5 seconds, add a zero for 15 seconds
});
所以它会是这样的:
var messages = [
"Please wait while we handle your request...",
"This is taking longer than usual to process - please wait...",
"We seem to be having trouble - please click <a href="/help.html">here</a> to contact support"`
有办法做到这一点吗?
最佳答案
当然,你必须:
- 修复转义字符串中的引号 (
"
) (\"
)。 - 使用
html:
而不是text:
.
首先,编辑您的 messages
像这样的变量:
var messages = [
"Please wait while we handle your request...",
"This is taking longer than usual to process - please wait...",
"We seem to be having trouble - please click <a href=\"/help.html\">here</a> to contact support"
];
然后编辑您的代码以创建 <p>
像这样的元素:
$('<p />', {html : message});
关于javascript - 在 JavaScript 变量中添加 HTML 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25108167/