将 html 标签添加到文本区域中选定的文本。为什么“if(‘selectionStart’ in textarea)”会这样?需要在里面吗?
我发现 JavaScript 代码允许我在 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>
我的问题与这一行有关,if('selectionStart' in textarea){:
- 这行代码到底是什么意思?
- 为什么
selectionStart
必须用引号引起来? selectionStart
通常附加到像这样的对象"textarea"(textarea.selectionStart)
,如何引用 到 它本身?If(X in Y){}
是标准 JavaScript 语法还是有效 专门用于selectionStart
?
注意:我正在 jsfiddle 中测试这个
I found javascript code that allows me to add html tags around text that I have highlighted in the textarea
field:
<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){
:
- What does the line mean exactly?
- Why does
selectionStart
have to be in quotes? selectionStart
is usually appended to an object like"textarea"(textarea.selectionStart)
, how is it possible to refer
to
it by itself?- Is
If(X in Y){}
standard javascript syntax or does it work
specifically forselectionStart
?
note: I'm testing this in jsfiddle
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
if('selectionStart' in textarea)
是功能测试 - 它检查textarea
对象是否具有selectionStart
属性。它需要用引号引起来,否则它将被解释为变量(在当前上下文中可能存在也可能不存在)。
这取决于浏览器以及支持和呈现的 HTML 版本。
是的,这是正常的 JavaScript 语法。它用于测试指定的属性是否在对象中。请参阅 MDN 上的
in
。< /p>if('selectionStart' in textarea)
is feature testing - it checks whether thetextarea
object has aselectionStart
property.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).
It depends on the browser and what version of HTML is supported and rendered.
Yes it is normal javascript syntax. It is used to test if the specified property is in the object. See
in
on MDN.