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