1

我正在创建一个个人资料页面,将所有<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><p>标签设置一个 ID(因为它们代表配置文件的不同部分)。我遇到的问题是为这些添加一个 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);

      }

    });

});
4

1 回答 1

0

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

$(".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();

});

它有效。快乐的时光。

于 2013-08-26T21:10:30.683 回答