背景
我正在创建一个
@Name
我的网页的标记系统。我已经成功地找到击键的名字并将内容替换为等效的 div class='tag' data-id='User-id'>Name</div>
(至少用于显示)。现在在提交来自 contentEditable
的那些内容之前分区我在 textarea
中修改它们(通常是隐藏的)。
工作
一旦
.keyup
事件发生在 contentEditable
contentEditable
的全部内容由函数处理 MakeItForWeb(contentEditable)
.然后操纵 textarea
的内容将由服务器端处理php
脚本。那php
脚本将去除所有标签,然后将数据存储在数据库中。所以在提交之前,我尝试替换所有 .tag
div 数据格式如下:
@["id":"User-id","Tag":"User-Name"];
在<textarea>
,我创建了一个 regular expression
在 javascript
完成任务。当有单个 .tag
时,它工作正常在单行中,你可以看到它 Here .
问题
当超过 1
.tag
在一行中出现,然后是 My regex
无法正确识别所有这些,只能识别最后一个。因此整个标记系统崩溃,你可以看到它Here .可能是我的方法不对。请问这里的高手可以帮帮我吗?欢迎任何建议。
我的努力(代码)
JavaScript + JQuery
:
$(document).ready(function(){
$("body").attr("spellcheck","false");
$("#tarea").keyup(function(e){ // Process KeyUp Event
/* Code to find Names on @N..and create a tag is omitted purposefully as it is working fine */
// Make each tag Un-editable, So that User cant change it
$(".tag").each(function(){
$(this).attr("contentEditable","false");
});
//Manipulate the textarea with equivalent value
MakeItForWeb(this);
}).focus(function(){
//Manipulate the textarea with equivalent value from contentEditable
MakeItForWeb(this);
});
$("#tarea").trigger("keyup"); // Trigger keyUp event as soon as DOM ready.
});
function MakeItForWeb(x){
var htm=$(x).html(); // Contents of contentEditable
htm=htm.split("<br>").join("\n"); // Replace <br> with \n character
htm=htm.split(" ").join(" ");
htm=htm.trim(); // Trim contents
/* Here is My regex which does the mentioned task */
htm=htm.replace(/<div(.*) data-id=\"(.*)\" (.*)>(.*)<\/div>/g,"@['id':'$2','tag':'$4'];");
document.getElementById("opc").value=htm; // <textarea> = ContentEditable processed.
}
注意这一行:
htm=htm.replace(/<div(.*) data-id=\"(.*)\" (.*)>(.*)<\/div>/g,"@['id':'$2','tag':'$4'];");
// This is My Regex.
// where var htm=contentEditable.innerHTML;
HTML
:
<div id="tarea" contentEditable="true" class="tarea" autocorrect="false" spellCheck="off">
Hello Says! <div class="tag" data-id="1005">Vedant Terkar</div> , <br />To all <div class="tag" data-id="1006">SO Users</div> :-).
</div>
<!-- This textarea is Usually Hidden -->
<textarea id="opc" rows="5" cols="97">
</textarea>
css
与问题无关,所以不发布。
希望这里的专家能帮帮我。提前致谢:-)!
最佳答案
正则表达式:
<div\b.*?\bdata-id=\"([^"]*)\">([^<]*).*?\/>([^<]*)<div\b.*?\bdata-id=\"([^"]*)\">([^<]*).*
替换字符串:
@['id':'$1','tag':'$2']; , $3@['id':'$4','tag':'$5'];
关于javascript - 用于在 contentEditable 中提取特定属性和 div 的 innerHTML 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24973894/