gpt4 book ai didi

javascript - 将 html 标签添加到文本区域中选定的文本。为什么 "if(' SelectionStart' in textarea)"需要在那里?

转载 作者:行者123 更新时间:2023-12-02 20:04:30 24 4
gpt4 key购买 nike

我发现 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){:

  1. 这句话的确切含义是什么?
  2. 为什么 selectionStart 必须用引号引起来?
  3. selectionStart 通常附加到像这样的对象 "textarea"(textarea.selectionStart),如何引用到 它本身?
  4. If(X in Y){} 是标准 JavaScript 语法还是有效 专门用于selectionStart

注意:我正在 jsfiddle 中测试它

最佳答案

  1. if('selectionStart' in textarea) 是功能测试 - 它检查 textarea 对象是否具有 selectionStart 属性。

  2. 它需要用引号引起来,否则它将被解释为变量(当前上下文中可能存在也可能不存在)。

  3. 这取决于浏览器以及支持和呈现的 HTML 版本。

  4. 是的,这是正常的 JavaScript 语法。它用于测试指定的属性是否在对象中。请参阅in在 MDN 上。

关于javascript - 将 html 标签添加到文本区域中选定的文本。为什么 "if(' SelectionStart' in textarea)"需要在那里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7619063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com