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){
:
- 什麼行是什麼意思?
- 爲什麼
selectionStart
必須用引號引起來? selectionStart
通常被附加到的物體像"textarea"(textarea.selectionStart)
,它是如何能夠通過自身來指 到 呢?- 是
If(X in Y){}
標準javascript語法還是可以工作 專門爲selectionStart
?
注:我測試這一點的jsfiddle
如果它在引號中,'selectionStart'不會被解釋爲字符串而不是對象的屬性嗎? – user701510
@ user701510 - 這就是它應該做的。它通過_name_查找屬性。 – Oded