2014-03-24 44 views
0

我目前使用的是html5文本編輯器(bootstrap-wysihtml5)。我試圖使用「按鍵」事件(在標籤上)在文本編輯器中選擇特定的單詞。jQuery選擇標籤文本編輯器中的文本(在div標籤內)事件

這裏是我的文字的例子:

<div> 
    My name is {{name}} and I enjoy {{programming in Rails}}. 
</div> 

<div> 
    {{Friend Name}} suggested that we get in touch to {{catch up}}. 
    He spoke {{highly}} about you and said that we should {{get together sometime}}. 
</div> 

目標:在 '按鍵' 選項卡中的事件,突顯中的每個字{{}}。 即 1.按一次標籤,高亮顯示{{姓名}}。 2.第二次按tab,高亮顯示{{rails in rails}},&等。

這是我到目前爲止執行:

$('#wysihtml5').each(function(i, elem) { 
    $(elem).wysihtml5({ 
    "font-styles": true, 
    "events": { 
     "focus": function() { 
     $('.wysihtml5-sandbox').contents().find('body').on("keydown",function(event) {   
      event.preventDefault(); 

      var numLoops = _.size($(this).children());    
      var keyCode = event.keyCode || event.which;    
      if (keyCode == 9){ 
      // loop thru all children divs 

      for (var i = 0; i < numLoops; i++) { 
       // get array of all matched items {{}} 

       var sentence = $($(this).children()[i]).html(); 
       var toSwap = sentence.match(/\{{(.*?)\}}/g); 
       var numSwap = _.size(toSwap); 
       // NEED TO FIGURE OUT: How to select matched item..and move to the next one on tab   
      }       
      }  
     });        
     } 
    } 
    }); 
}); 

有什麼想法?我已經花了2天的時間找到如何完成這項工作。我已經看過下面是引用:

回答

1

你想要什麼是正則表達式的指數相匹配。

如果執行的正則表達式如下:

var reg = /\{{(.*?)\}}/g; // The Regex selector 

while(match=reg.exec(sentence)) { // Iterate all the matched strings 

    // match.index gives the starting position of the matched string 
    // match.length gives the length of the matched string, number of characters 

} 

您將獲得可用於選擇的所有匹配的位置和長度。 while循環迭代所有匹配。

保存匹配項並使用它們的索引和長度值逐個選擇它們。

編輯 再次回來。正如你可能已經經歷的那樣,在javascript中選擇文本並不是最簡單的任務,但它完全可行。

我把一個小JSFiddle放在一起來演示我用來獲得正確結果的技術。你可以找到它here。 我希望它很清楚,我試圖評論它。

當然,如果您有任何問題,請問!

乾杯!

+0

感謝您的迴應Fabian!這很有道理 - 但是,如何突出顯示/選擇單詞(即{{name}}),以便您可以立即選擇單詞(如鼠標單擊這些單詞以便可以鍵入並覆蓋這些單詞)?讓我知道你的想法,謝謝! –

+0

目前在上課時,會盡快回復您! –

+0

@AlvinAng我剛剛更新了我的答案,以包括選擇。請問是否有任何問題/問題! –