编写JavaScript代码与其他操作系统有何不同;s

编写JavaScript代码与其他操作系统有何不同;s,javascript,Javascript,我有本书第18章中的以下代码片段。表单和表单字段,在这些字段中,它假定在键下插入字符串 // Input field <textarea></textarea> // The following code wires up // a <textarea> tag with an event handler that, when you press F2, inserts // the string “Khasekhemwy” for you. var te

我有本书第18章中的以下代码片段。表单和表单字段,在这些字段中,它假定在键下插入字符串

// Input field
<textarea></textarea>

// The following code wires up
// a <textarea> tag with an event handler that, when you press F2, inserts
// the string “Khasekhemwy” for you.

var textarea = document.querySelector('textarea');
textarea.addEventListener('keydown', function(event) {
// The key code for F2 happens to be 113
if (event.keydown == 113) {
    replaceSelection(textarea, "Khasekhemwy");
    event.preventDefault();
    }
});

// The replaceSelection function replaces the currently selected part of a
// text field’s content with the given word and then moves the cursor after
// that word so that the user can continue typing.

function replaceSelection(field, word ) {
    var from = field.selectionStart, to = field.selectionEnd;
    field.value = field.value.slice(0, from ) + word +
                                field.value.slice(to);
    // Put the c u r s o r after the word
    field.selectionStart = field.selectionEnd = from + word.length;
}
//输入字段
//下面的代码连接起来
//带有事件处理程序的标记,当您按F2键时,该标记将插入
//字符串“Khasekhemwy”是给你的。
var textarea=document.querySelector('textarea');
textarea.addEventListener('keydown',函数(事件){
//F2的键代码恰好是113
如果(event.keydown==113){
替换选择(文本区域,“Khasekhemwy”);
event.preventDefault();
}
});
//replaceSelection函数替换当前选定的零件
//文本字段的内容,然后将光标移动到
//这样用户就可以继续键入。
函数替换选择(字段、字){
变量from=field.selectionStart,to=field.selectionEnd;
field.value=field.value.slice(0,from)+word+
field.value.slice(to);
//把c u r s o r放在单词后面
field.selectionStart=field.selectionEnd=from+word.length;
}
我在Macintosh电脑上使用最新的浏览器,我开始感觉到这段代码不是写在不同的操作系统上,就是写在不同的操作系统上


注意:在Macintosh上调用F2=
fn+F2

您输入了错误的代码(复制时?)。它应该是
if(event.keyCode==113)
而不是
if(event.keydown==113)


event.keydown
可能总是计算为
undefined
,因此该条件永远不会为真。

正确答案将为yes。但不在你问题的范围之内

JS执行结果取决于谁将执行您的JS。在您的问题中,您使用的是DOM,因此我假设您使用的是browser。在这种情况下,浏览器将是您的执行器,根据浏览器的不同,执行结果可能会有所不同(特别是对于DOM操作)

第二点是,我们并不总是在浏览器的范围内执行JS。中的另一种常用方法是使用Node.Js。在这种情况下,对于节点的不同版本,执行可能会有所不同

第三点。Windows(作为操作系统)可以自己执行JS。所以这个执行的结果将与Mac完全不同:)


请注意,JS不是编译,因此相同的代码在不同的环境中可能表现不同

这是否仅当您调用
F*
或任何其他键时才发生?事件的值是多少。键?事件没有keydown属性,这就是它不起作用的原因。也就是说,使用keyCode也不推荐:“此功能已从Web标准中删除。尽管某些浏览器可能仍然支持它,但它正在被删除。避免使用,并尽可能更新现有代码;请参阅本页底部的兼容性表以指导您的决策。请注意,此功能可能随时停止工作。“我发现您的答案在@DomK中很有用,它与此有关,还有更多。因为JS确实依赖于执行者。