简体   繁体   English

“选择”是 JavaScript 中的保留关键字吗?

[英]Is "choose" a reserved keyword in JavaScript?

I'll explain myself: I'm building a simple web, and at some point in the HTML I have this我会解释一下自己:我正在构建一个简单的 web,并且在 HTML 的某个时刻我有这个

<button id="choose" type="button" onclick="choose()">Choose</button>

In the <head> I added a script file so it knows where to find the choose() function在 <head> 我添加了一个脚本文件,所以它知道在哪里可以找到 choose() function

<script src="scripts.js"></script>

And lastly in that scripts.js file I defined the next function:最后在该 scripts.js 文件中,我定义了下一个 function:

function choose() {
    choices = document.getElementById("choices");
    console.log(choices)
}

Now here it comes the problem.现在问题来了。 When I click the button, in the console I get an "Uncaught TypeError: choose is not a function", but just by deleting for example the last "e" in the function name it works perfectly.当我单击按钮时,在控制台中我得到一个“未捕获的类型错误:选择不是函数”,但只需删除 function 名称中的最后一个“e”,它就可以完美地工作。

I don't mind at all changing the name, but I'm really curious of what's happening.我完全不介意更改名称,但我真的很好奇发生了什么。

Edit: some people are focusing on the "choices" element that isn't seen in the code I provided, but that's not he problem (in fact just by changing the name of the function it works).编辑:有些人专注于我提供的代码中没有看到的“选择”元素,但这不是他的问题(实际上只是通过更改 function 的名称就可以了)。 Anyway, here is the complete body code:无论如何,这是完整的正文代码:

<body>
    <form>
        Introduce one element in each line:<br/>
        <textarea id="choices" rows="10" cols="70"></textarea><br/><br/>
        <button id="choose" type="button" onclick="choose()">Choose</button>
    </form>
    <div id="result"></div>
</body>

And by the way, for me it happens in Firefox too.顺便说一句,对我来说,它也发生在 Firefox 中。

No "choose" is not a reserved keyword in javascript, but in the code, you mentioned we are unable to find choices ID, please be in brief so that we can help you. No "choose" 不是 javascript 中的保留关键字,但是在代码中,您提到我们无法找到选择 ID,请简要说明,以便我们为您提供帮助。

and instead of document.getElementById("choices") alternatively you can use this below syntax而不是 document.getElementById("choices") 或者你可以使用下面的语法

document.querySelector("#choices"); document.querySelector("#choices");

even though I have proper code received from you I'm trying my best to give this answer, please see the below code即使我从您那里收到了正确的代码,我也在尽力给出这个答案,请参阅下面的代码

// html
<button id="choices" type="button" onclick="choose()">Choose</button>

// javascript
function choose() {
    choices = document.querySelector("#choices");
    console.log(choices);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM