问题
I am learning JavaScript, I have reached a section called "creating objects", since I am a novice in programming I cant figure out how to trigger the "prompt" request by using a button, instead of being triggered when the page loads, any idea?
myobjt = new Object();
var reqPrompt = prompt("Type a word:");
myobjt.mnfstInput = reqPrompt;
function mFunc() {
document.write(this.mnfstInput);
}
myobjt.mnfstScreen = mFunc;
myobjt.mnfstScreen();
回答1:
While both of the other answers are correct, and are a very good way to do it, I'll try to answer using an object
<script>
var myObject = {
input: "",
popup: function(){
alert("Hello, " + this.input);
},
setInput: function(){
this.input = prompt("Enter Name");
}
}
</script>
<button type="button" onclick="myObject.setInput()">Input</button>
<button type="button" onclick="myObject.popup()">Output</button>
Edit: https://jsfiddle.net/u1yfsp4z/4/
回答2:
In your html create a button
<button id="btn">Click me</button>
In javascript add an event handler:
document.getElementById('btn').addEventListener("click", function(){
var question = prompt("What is the meaning of life?");
//do whatever you want to do with the answer
});
回答3:
Add a button in your HTML like this one:
<button id="clickMe">click here!</button>
Then retrieve this button in your script and use an event listener to listen the click events:
var button = document.getElementById('clickMe');
button.addEventListener('click', trigger);
function trigger() {
// all your code :)
}
回答4:
You could use HTML onclick
attribute on the button
<button onclick='add()'>Add property</button>
I noticed that you are using document.write
, keep in mind document.write
will overwrite the whole page.
var myobjt = new Object();
function add(){
var reqPrompt = prompt("Type a word:");
myobjt.newProp = reqPrompt;
mFunc();
}
function mFunc() {
document.getElementById('result').innerHTML = JSON.stringify(myobjt);
}
<button onclick='add()'>Add property</button>
<div id='result'></div>
来源:https://stackoverflow.com/questions/36670653/javascript-trigger-request-with-a-button