【问题标题】:jQuery to select text (inside a div tag) within text editor on tab eventjQuery 在选项卡事件的文本编辑器中选择文本(在 div 标签内)
【发布时间】:2014-05-02 12:42:48
【问题描述】:

我目前正在使用 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”标签事件中,突出显示 {{ }} 中的每个单词。 IE。 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 天的时间来寻找如何使这项工作。以下是我看过的参考资料:

【问题讨论】:

    标签: javascript jquery regex bootstrap-wysihtml5


    【解决方案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。 我希望它有点清楚,我试图很好地评论它。

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

    干杯!

    【讨论】:

    • 感谢您的回复费边!这是有道理的 - 但是,您如何突出显示/选择单词(即 {{name}})以便您可以立即选择这些单词(就像鼠标单击这些单词以便您可以键入和覆盖这些单词)?让我知道你的想法,谢谢!
    • 正在上课,会尽快回复您!
    • @AlvinAng 我刚刚更新了我的答案以包括选择。只要问有什么问题/问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多