编写JavaScript代码与其他操作系统不同吗?

问题描述 投票:1回答:2

我在本书Eloquent JavaScript,第18章中有以下代码片段。表单和表单字段,它假设在keydown上插入一个字符串。

// 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;
}

我在使用最新浏览器的Macintosh计算机上,我开始意识到这是代码编写的不同操作系统,或者是代码。

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

javascript
2个回答
-1
投票

正确的答案是肯定的。但不在你的问题范围内。

JS执行基于谁将执行你的JS的结果。在您的问题中,您正在使用DOM,因此我假设您使用浏览器。在这种情况下,浏览器将是您的执行程序,执行结果可能不同(特别是对于DOM操作),具体取决于浏览器。

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

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

请注意,JS不是编译器,因此相同的代码在不同的环境中可能会有不同的行为。


2
投票

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

event.keydown可能总是评估为undefined,因此条件永远不会成立。

© www.soinside.com 2019 - 2024. All rights reserved.