[英]adding html tags to selected text in textarea. Why does “if('selectionStart' in textarea)” need to be in there?
I found javascript code that allows me to add html tags around text that I have highlighted in the textarea
field: 我找到了javascript代码,允许我在textarea
字段中突出显示的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>
My questions pertain to this line, if('selectionStart' in textarea){
: 我的问题属于这一行, if('selectionStart' in textarea){
:
selectionStart
have to be in quotes? 为什么selectionStart
必须在引号中? selectionStart
is usually appended to an object like "textarea"(textarea.selectionStart)
, how is it possible to refer to it by itself? selectionStart
通常附加到像"textarea"(textarea.selectionStart)
这样的对象上,如何自己引用它? If(X in Y){}
standard javascript syntax or does it work specifically for selectionStart
? If(X in Y){}
标准javascript语法还是专门用于selectionStart
? note: I'm testing this in jsfiddle 注意:我在jsfiddle中测试它
if('selectionStart' in textarea)
is feature testing - it checks whether the textarea
object has a selectionStart
property. if('selectionStart' in textarea)
是特征测试 - 它检查textarea
对象是否具有selectionStart
属性。
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. 这取决于浏览器以及支持和呈现的HTML版本。
Yes it is normal javascript syntax. 是的,这是正常的JavaScript语法。 It is used to test if the specified property is in the object. 它用于测试指定的属性是否在对象中。 See in
on MDN. 见in
上MDN。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.