2011-10-01 84 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

相關問題