如何通过弹出窗口获取输入并通过 javascript/jquery 将文本放入变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11363732/
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-08-24 05:37:55  来源:igfitidea点击:

How to get input via a popup and place text in a variable via javascript/jquery

javascriptjquerypopup

提问by Mark

I have a button on my page. When clicked a popup box should appear allowing the user to enter text. When OK/Submit is pressed, my jscript will then perform some functions using that inputted data. Very straightforward, but I just can't figure out how to do this.

我的页面上有一个按钮。单击时,应出现一个弹出框,允许用户输入文本。当按下 OK/Submit 时,我的 jscript 将使用输入的数据执行一些功能。非常简单,但我就是不知道如何做到这一点。

Thanks!

谢谢!

回答by Reinder Wit

in it's simplest form, you could use prompt(question, default): (taken from w3schools: http://www.w3schools.com/js/tryit.asp?filename=tryjs_prompt)

以最简单的形式,您可以使用prompt(question, default):(取自 w3schools:http: //www.w3schools.com/js/tryit.asp?filename =tryjs_prompt )

function myFunction(){
    var x;
    var name=prompt("Please enter your name","Harry Potter");
    if (name!=null){
       x="Hello " + name + "! How are you today?";
      alert(x);
   }
}

anything else would require lots of javascript & CSS to create layers with buttons and click events on those buttons

其他任何事情都需要大量的 javascript 和 CSS 来创建带有按钮的图层并在这些按钮上单击事件

回答by The Alpha

Paste this code inside your headtags between scripttags

将此代码粘贴到head标签之间的script标签中

HTML

HTML

<button id="button">Get Text</button>?

JS

JS

window.onload=function()
{
    var el=document.getElementById('button');
    el.onclick=function(){
        var my_text=prompt('Enter text here');
        if(my_text) alert(my_text); // for example I've made an alert
    }
}

DEMO.

演示。