Chrome不能找到firefox和eclipse的功能

Chrome can not find function firefox and eclipse does

本文关键字:eclipse 功能 firefox 不能 Chrome      更新时间:2023-09-26

我希望我笨拙的业余代码不会冒犯你,但是我正在编写一个非常简单的Caesar密码程序,并且我遇到了一个奇怪的问题。当我在eclipse或Firefox中运行此页面时,它工作得很好,但当我在chrome中运行它时(因此我可以利用我所知道的开发工具),当我单击按钮时,它找不到翻译功能。

index.html:62 Uncaught TypeError:翻译不是一个函数

知道发生了什么事吗?

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Decoder Ring Program</title>
<meta http-equiv="content-type" 
content="text/html;charset=utf-8" />
<style>
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
    codeWheel = "abcdefghijklmnopqrstuvwxyz";
    $(document).ready(function(){
        document.getElementById('codeWheel').innerHTML = codeWheel.toUpperCase();
    });
    function isAlpha(str) {
        return str.length === 1 && str.toLowerCase().match(/[a-z]/i);
    }
    function translate() {
        plaintext = document.getElementById('inputText').value.toLowerCase();
        key = document.getElementById('key').value.toLowerCase().charCodeAt() - 'a'.charCodeAt();
        translated = "";
        direction = document.querySelector('input[name = "direction"]:checked').value;
        for (i = 0; i < plaintext.length; i++) {
            letter = plaintext[i];
            letterValue = plaintext[i].charCodeAt() - 'a'.charCodeAt();
            if (!isAlpha(plaintext[i])) {
                translated += letter;
            } else {
                if (direction == 'encode') {
                    translated += codeWheel[(letterValue + key) % 26];
                } else {
                    index = codeWheel.indexOf(letter);
                    translated+= String.fromCharCode('a'.charCodeAt() + (26 + index - key) % 26);
                }
            }
        }
        document.getElementById('output').innerHTML = translated.toUpperCase();
    }
</script>
</head>
<body>
    <h1>Decoder Ring</h1>
    <div id="codeWheel"></div>
    <hr/>
    <div>
        PlainText <input type="text" name="inputText" id="inputText"></input><br/>
        Key <input type="text" name="key" id="key"></input>
        <form>
            <input type="radio" name="direction" value="encode" checked>Encode
            <input type="radio" name="direction" value="decode" >Decode
        </form>
        <button onclick="translate()">Translate</button>
    </div>
    <hr/>
    <div id="output"></div>
</body>
</html>

显然,这是因为在on*属性的上下文中,触发事件的元素的属性会遮蔽全局变量。

快看!:

var id = "I get shadowed";
<button id="testing" onclick="alert(id)">click me</button>

在Chrome中,translatebutton的布尔属性,但Firefox没有这样的属性。

你可能听说过onclick和公司是不好的做法,我建议使用addEventListener代替。或者,您可以将函数名更改为不会发生冲突的名称,或者使用onclick="window.translate()"