0

我正在使用测试和替换方法来检测和替换文本中的标签,但替换方法返回与标签关联的文本,而应该只返回没有标签的文本!为什么?

我的jQuery插件:

jQuery.fn.extend({
insertTag: function(Tag){
    var pattern = new RegExp("\[("+Tag+")\](.*?)\[\/("+Tag+")\]","gi");

    return this.each(function (i) {
        var sel,ptrn;

        if (document.selection) {
            this.focus();
            sel = document.selection.createRange();
            sel.text = '['+Tag+']' + sel.text + '[/'+Tag+']';
        }
        else if (this.selectionStart || this.selectionStart == '0') {
            this.focus();
            var startPos = this.selectionStart, endPos = this.selectionEnd;
            sel = this.value.substring(startPos, endPos);
            alert(sel); // show seleced text for debug ing!

            if(pattern.test(sel)){
              txt = sel.replace(pattern,"$1");
              alert(txt); // show replaced text for debug ing!

              this.value = this.value.substring(0, startPos) + (txt) + this.value.substring(endPos, this.value.length);

            }else{
            this.value = this.value.substring(0, startPos) + ('['+Tag+']' + sel + '[/'+Tag+']') + this.value.substring(endPos, this.value.length);

            }
        }
    })
}

});

此部分用于删除选定文本中的标记(如果存在):

if(pattern.test(sel)){
              txt = sel.replace(pattern,"$1");
              alert(txt); // show replaced text for debug ing!

              this.value = this.value.substring(0, startPos) + (txt) + this.value.substring(endPos, this.value.length);

            }

但它不能正常工作......

例如 :

txt = $("#txt");

txt.insertTag(b):

[b]some text[/b]

txt.insertTag(b):

[]some text[/b]

而回到“一些文字”

谢谢你的帮助 :)

4

0 回答 0