一千萬個為什麽

搜索

BB Code Parser(在格式化階段),jQuery因為混亂的循環而被卡住

大家問候, 我正在制作一個BB Code Parser,但我仍然堅持使用JavaScript。我正在使用jQuery和插入庫來記錄文本字段中的選擇。當有人選擇一段文本時,將出現帶有格式選項的div。

I have two issues.
Issue 1. How can I make this work for multiple textfields? I'm drawing a blank as it currently will detect the textfield correctly until it enters the

$("#BBtoolBox a").mousedown(function() { }

循環。進入後,它將開始以我的眼睛隨機模式逐個列出一個字段。

!!! MAIN Issue 2. I'm guessing this is the main reason for issue 1 as well. When I press a formatting option it will work on the first action but not the ones afterwards. It keeps duplicating the variable parsed. (if I only keep to one field it will never print in the second)

Issue 3 If you find anything especially ugly in the code, please tell me how to improve myself.

我贊賞我能得到的所有幫助。提前致謝

$(document).ready(function() {
    BBCP();
});

function BBCP(el) {
    if(!el) { el = "textarea"; }
   //Stores the cursor position of selection start

    $(el).mousedown(function(e) {
    coordX = e.pageX;
    coordY = e.pageY;

   //Event of selection finish by using keyboard
    }).keyup(function() {
        BBtoolBox(this, coordX, coordY);

   //Event of selection finish by using mouse
    }).mouseup(function() {
        BBtoolBox(this, coordX, coordY);

   //Event of field unfocus
    }).blur(function() {
        $("#BBtoolBox").hide();

    });

}

function BBtoolBox(el, coordX, coordY) {
   //Variable containing the selected text by Caret
    selection = $(el).caret().text;
   //Ignore the request if no text is selected
    if(selection.length == 0) {
        $("#BBtoolBox").hide();
        return;
    }
   //Print the toolbox
    if(!document.getElementById("BBtoolBox")) {
        $(el).before("<div id=\"BBtoolBox\" style=\"left: "+ ( coordX + 5 ) +"px; top: "+ ( coordY - 30 ) +"px;\"></div>");
       //List of actions
        $("#BBtoolBox").append("\"B\"");
        $("#BBtoolBox").append("\"I\"");

    } else {
        $("#BBtoolBox").css({'left': (coordX + 3) +'px', 'top': (coordY - 30) +'px'}).show();
    }

   //Parse the text according to the action requsted
    $("#BBtoolBox a").mousedown(function() {
        switch($(this).children(":first").attr("alt"))
        {
            case "B"://bold
                parsed = "[b]"+ selection +"[/b]";
                break;
            case "I"://italic
                parsed = "[i]"+ selection +"[/i]";
                break;
        }

       //Changes the field value by replacing the selection with the variable parsed
        $(el).val($(el).caret().replace(parsed));
        $("#BBtoolBox").hide();
        return false;
    });
}

最佳答案

這一行: $(“#BBtoolBox a”)。mousedown(function()將一個函數附加到鏈接。但是,這行多次運行,每次它運行它將另一個函數附加到鏈接,留下重復的文本。

An optimal solution is to use a plugin, for example (the first one I found): http://urlvars.com/code/example/19/using-jquery-bbcode-editor (demo)

轉載註明原文: BB Code Parser(在格式化階段),jQuery因為混亂的循環而被卡住