0

我目前正在使用 html5 文本编辑器 ( bootstrap-wysihtml5 )。我正在尝试使用“按键”事件(在选项卡上)在文本编辑器中选择特定单词。

这是我的文本示例:

<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>

目标:在“keypress”选项卡事件中,突出显示 {{ }} 中的每个单词。即 1. 按 Tab 一次,将突出显示 {{name}}。2. 第二次按 Tab 键,将突出显示 {{programming 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 天的时间来寻找如何使这项工作。以下是我看过的参考资料:

4

1 回答 1

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 来演示我用来获得正确结果的技术。你可以在这里找到它。我希望它有点清楚,我试图很好地评论它。

当然,如果你有任何问题,尽管问!

干杯!

于 2014-03-24T23:03:08.723 回答