Javascript onClick 提示框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17778921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:36:16  来源:igfitidea点击:

Javascript onClick prompt boxes?

javascript

提问by Omar Al-Naimi

How do I change that prompt box script into an onClick prompt?

如何将该提示框脚本更改为 onClick 提示?

<script> 
var name = prompt("What's Your Name");
var name1 = function (name) {
confirm("Great to see you," + " " + name);
};
name1(name)
</script>

please keep the script as it is, since this is the only way I could understand it.

请保持脚本原样,因为这是我理解它的唯一方式。

回答by carl-lopez

You'd first need to use a html element to hook the onClick event to, let's use a plain button here:

您首先需要使用一个 html 元素来挂钩 onClick 事件,让我们在这里使用一个普通按钮:

<input type="button" onClick="name1(name);" value="Confirm Test" />

and pass on the function you created to the event.

并将您创建的函数传递给事件。

These events can take in javascript blocks of code and execute it when the event arises, I'd also recommend taking a look at the specs like the one @David is suggesting.

这些事件可以接收 javascript 代码块并在事件发生时执行它,我还建议您查看@David 建议的规范。

回答by leoMestizo

Is a best practiceadd the "behavior" in a external JavaScript file and NOTlike a HTML attribute.

最佳做法是在外部 JavaScript 文件中添加“行为”,而不是HTML 属性那样

For do that, just add the follow JavaScript code (in a external file):

为此,只需添加以下 JavaScript 代码(在外部文件中):

document.getElementById("button").onclick = function() { /* code */ }

Where the markup is:

标记在哪里:

<button id="button" type="submit">Click me!</button>

For "linking" that JavaScript code in your HTML page, just add the file with your code in the scriptelement:

要在 HTML 页面中“链接”该 JavaScript 代码,只需在script元素中添加带有代码的文件:

<script src="Your relative path (or absolute if you want)"></script>

Speaking of best practices, add the scriptelement before the body close tag; NOTin the headelement. With this way you'll avoid that the render of the page have to wait for the load of the JS files.

说到最佳实践,scriptbody close 标签之前添加元素;不要head元素。通过这种方式,您将避免页面的渲染必须等待 JS 文件的加载。

Here's an example: Fiddle

这是一个例子:小提琴

BTW, you don't need to create all those variables:

顺便说一句,您不需要创建所有这些变量:

document.getElementById("button").onclick = function() {
    confirm("Great to see you," + " " + prompt("What's Your Name"));
};