2011-10-01 82 views
0

我发现JavaScript代码,让我补充身边,我在textarea领域都强调文本的HTML标签:将html标签添加到textarea中的选定文本。为什么“if('textarea中的selectionStart')”需要在那里?

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

我的问题是关于这一行,if('selectionStart' in textarea){

  1. 什么行是什么意思?
  2. 为什么selectionStart必须用引号引起来?
  3. selectionStart通常被附加到的物体像 "textarea"(textarea.selectionStart),它是如何能够通过自身来指 到 呢?
  4. If(X in Y){}标准javascript语法还是可以工作 专门为selectionStart

注:我测试这一点的jsfiddle

回答

2
  1. if('selectionStart' in textarea)是功能测试 - 它检查textarea对象是否具有selectionStart属性。

  2. 它需要用引号括起来,否则它会被解释为一个变量(可能存在或不存在于当前上下文中)。

  3. 它取决于浏览器以及支持和呈现哪个版本的HTML。

  4. 是的,这是正常的JavaScript语法。它用于测试指定的属性是否在对象中。请参阅MDN上的in

+0

如果它在引号中,'selectionStart'不会被解释为字符串而不是对象的属性吗? – user701510

+1

@ user701510 - 这就是它应该做的。它通过_name_查找属性。 – Oded

相关问题