[英]Link html button to javascript
I have a project on jsFiddle in which I want to link a button to the following Javascript code: 我在jsFiddle上有一个项目,我想在其中将按钮链接到以下Javascript代码:
var computerChoice = math.random();
if (computerChoice < 0,5) {
console.log("you lost")
} else {
console.log("you've won"
}
So if I press the button, a random number should be generated leading to one of the two responses. 因此,如果按下按钮,则应生成一个随机数,导致出现两个响应之一。 How can I get this working? 我该如何工作?
$('#yourButton').click(function(){
// insert your JS here
})
To elaborate...the above is attaching a click event listener to your button. 详细说明...上面是将click事件监听器附加到您的按钮上。 This is the very essence of jQuery: select an item from the DOM, attach logic to it. 这是jQuery的本质:从DOM中选择一个项目,并为其添加逻辑。 The above assumes you gave your button an id
of 'yourButton' but you could select the button in any number of ways using jQuery selectors (google that to find plenty of tutorials). 上面假设您给按钮指定了一个'yourButton'的id
,但是您可以使用jQuery选择器(可从Google那里找到很多教程)以多种方式选择按钮。
function tosser(){
if (Math.random() < 0.5) {
return "you lost";
} else {
return "you\'ve won";
}
}
$("button").on("click",function(){
alert(tosser());
});
I have a question about jquery. 我有一个关于jquery的问题。
I'm assuming you can use jQuery then. 我假设您可以使用jQuery。 Call the function on the click event: 在click事件上调用该函数:
function randomNumber(){
var computerChoice = Math.random();
if (computerChoice < 0.5) {
console.log("you lost")
} else {
console.log("you've won");
}
}
$("button").click(randomNumber);
Or: 要么:
var button = document.getElementById("button");
button.onclick = function(){
randomNumber();
}
Also, you need to capitalize the m
in Math
. 另外,您需要在Math
大写m
。
This might help you: 这可能对您有帮助:
<Br>
doesnt need to be closed <Br>
不需要关闭 user181796 have a nice rest of day! user181796休息愉快!
$('#Start').click(function(){
number = Math.random();
number = number.toFixed(1);
if (number < 0.5) {
console.log("you lost " + number);
} else {
console.log("you win " + number);
}
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<span> text box 1 </span>
<input class = "styleYellow" type = "text"> </input>
<br> <br>
<span> text box 1 </span><input type = "text"> </input>
<br> </br>
<button id="Start">Ga naar pagina 1</button>
<button id="I_dont_know">Ga naar pagina 2</button>
onclick refer to function: onclick是指功能:
HTML: HTML:
<button onclick="function1()"></button>
JAVASCRIPT: JAVASCRIPT:
function function1(){
var computerChoice = math.random();
if (computerChoice < 0,5) {
console.log("you lost");
}else {
console.log("you've won");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.