javascript - 正则表达式: transferring the data attribute

标签 javascript jquery regex

我正在创建一个更改所有 <strong>Title</strong> 的个人资料页面标签为 <input type="text" value="Title"><p>Content</p>标签为 <textarea>Content</textarea>标签。

这非常适合:

$(this).html(function(i, h) {
  return h
    .replace(/<strong>/g, "<input type=\"text\" value=\"")
    .replace(/<\/strong>/g, "\" class=\"profile-header\">")
    .replace(/<p>/g, "<textarea>")
    .replace(/<\/p>/g, "</textarea>");
});

但是,我需要为每组 <strong> 提供一个 ID和<p>标签(因为它们代表配置文件的不同部分)。我遇到的问题是为这些添加一个 ID,我已将其放在 <strong> 上。像这样的标签:<strong data-id="0">但无法弄清楚为什么我使用的正则表达式不能正常工作。

这是我到目前为止所做的,希望您能看到我想要实现的目标:

$(this).html(function(i, h) {
  return h
    .replace(/<strong data-id=\"(\i+)\">/g, "<input $1 type=\"text\" value=\"")
    .replace(/<\/strong>/g, "\" class=\"profile-header\">")
    .replace(/<p>/g, "<textarea>")
    .replace(/<\/p>/g, "</textarea>");
});

仅供引用,这就是我将 HTML 返回到其原始状态的方式(以及数据的保存方式):

$(".column.about input").each(function() {

    // Get the titles and content from the inputs and textareas
    var content_id = $(this).data("id");
    var title = $(this).val();
    var content = $(this).next().val();

    // We're changing the content first so we don't loose $(this)
    $(this).next().after("<p>" + content + "</p>").remove();
    $(this).after("<strong data-id=\"" + content_id + "\">" + title + "</strong>").remove();

    $.post("../includes/ajax.php", { action: "updateProfile", section: "about", id: content_id, title: title, content: content }).done(function(data) {

        if(data != "saved") {

        throwErrorMessage(data);

      }

    });

});

最佳答案

这是我所做的(没有正则表达式):

$(".column.about strong").each(function() {

    // Get the titles and content from the strong and p tags
    var content_id = $(this).data("id");
    var title = $(this).text();
    var content = $(this).next().text();

    // We're changing the content first so we don't loose $(this)
    $(this).next().after("<textarea>" + content + "</textarea>").remove();
    $(this).after("<input type=\"text\" data-id=\"" + content_id + "\" value=\"" + title + "\">").remove();

});

而且它有效。快乐的日子。

关于javascript - 正则表达式: transferring the data attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18452751/

相关文章:

javascript - 如何裁剪 canvas.toDataURL

javascript - 使用 JavaScript 进行幻灯片放映

javascript - 如何检测手机或移动设备?

javascript - 在js中用多个定界符和特殊字符分割

c++ - 使用正则表达式查找和替换

javascript - promise 后的重定向处理

javascript - 包含多个生成任务的 Grunt 任务将只运行第一个任务

javascript - 使用字符串的日期对象

javascript - 模拟来自 IFrame 的点击,以便打开一个新选项卡。

javascript - 带或不带 http 和 www 的 URL 验证