简体   繁体   English

将HTML标签添加到textarea中的选定文本。 为什么“if('textarea中的'selectionStart')”需要在那里?

[英]adding html tags to selected text in textarea. Why does “if('selectionStart' in textarea)” need to be in there?

I found javascript code that allows me to add html tags around text that I have highlighted in the textarea field: 我找到了javascript代码,允许我在textarea字段中突出显示的textarea周围添加html标记:

    <textarea id="myArea" cols="30" spellcheck="false">Select some text within this field.</textarea>
        <button onclick="ModifySelection ()">Modify the current selection</button>

<script>
      function ModifySelection () {
                var textarea = document.getElementById("myArea");
          if('selectionStart' in textarea){
          if (textarea.selectionStart != textarea.selectionEnd) {
                        var newText = textarea.value.substring (0, textarea.selectionStart) + 
                            "[start]" + textarea.value.substring  (textarea.selectionStart, textarea.selectionEnd) + "[end]" +
                            textarea.value.substring (textarea.selectionEnd);
                        textarea.value = newText;
                    }
                }
    }
</script>

My questions pertain to this line, if('selectionStart' in textarea){ : 我的问题属于这一行, if('selectionStart' in textarea){

  1. What does the line mean exactly? 这条线到底意味着什么?
  2. Why does selectionStart have to be in quotes? 为什么selectionStart必须在引号中?
  3. selectionStart is usually appended to an object like "textarea"(textarea.selectionStart) , how is it possible to refer to it by itself? selectionStart通常附加到像"textarea"(textarea.selectionStart)这样的对象上,如何自己引用它?
  4. Is If(X in Y){} standard javascript syntax or does it work specifically for selectionStart ? If(X in Y){}标准javascript语法还是专门用于selectionStart

note: I'm testing this in jsfiddle 注意:我在jsfiddle中测试它

  1. if('selectionStart' in textarea) is feature testing - it checks whether the textarea object has a selectionStart property. if('selectionStart' in textarea)是特征测试 - 它检查textarea对象是否具有selectionStart属性。

  2. It needs to be in quotes as otherwise it would be interpreted as a variable (which may or may not exist in the current context). 它需要在引号中,否则它将被解释为变量(在当前上下文中可能存在或可能不存在)。

  3. It depends on the browser and what version of HTML is supported and rendered. 这取决于浏览器以及支持和呈现的HTML版本。

  4. Yes it is normal javascript syntax. 是的,这是正常的JavaScript语法。 It is used to test if the specified property is in the object. 它用于测试指定的属性是否在对象中。 See in on MDN. in上MDN。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM