我正在创建一个更改所有 <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/