javascript - 在 JavaScript 变量中添加 HTML 代码?

标签 javascript jquery html

我只是想知道如何在 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"`

有办法做到这一点吗?

最佳答案

当然,你必须:

  1. 修复转义字符串中的引号 ( " ) ( \" )。
  2. 使用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/

相关文章:

javascript - async.waterfall 回调在哪里定义

c# - 用于多次上传的 JavaScript 问题

javascript - 使用 jquery 的问答游戏

javascript - 使用 NG-Repeat angularJS 进行 CSS 图像格式化

javascript - 使用覆盖 promise 默认捕获实现

javascript - 在javascript中解析QueryString

jquery - 从 jquery 中的 .ajax() 函数获取数据

javascript - 使用 AJAX 上传多个文件

javascript - 如何限制 Google Chrome 扩展弹出窗口的大小?

html - 图像调整到父 div 保持比例并尊重图像高度