admin管理员组

文章数量:1400044

I am a Bit Beginner In JavaScript. So I need a code about { If we clicked a button a function need to run} more of them suggested this but it still not working ! and I don`t know why? Can you solve it?

if(document.getElementById("btn").clicked == true){
//some code here
    console.log("working");
}
<button id=""btn>ClickEvent</button>

I am a Bit Beginner In JavaScript. So I need a code about { If we clicked a button a function need to run} more of them suggested this but it still not working ! and I don`t know why? Can you solve it?

if(document.getElementById("btn").clicked == true){
//some code here
    console.log("working");
}
<button id=""btn>ClickEvent</button>

Share Improve this question edited Apr 15, 2018 at 8:20 Clint 6,5391 gold badge24 silver badges29 bronze badges asked Mar 27, 2018 at 14:35 Manoj AManoj A 4322 gold badges5 silver badges13 bronze badges 2
  • You made a typo on id=""btn => id="btn" – Portekoi Commented Mar 27, 2018 at 14:37
  • oh ! that`s not a problem ! i have wrongly typed here but in my main code i have typed correctly!. Problem : {If i clicked it does not printing it in console} – Manoj A Commented Mar 27, 2018 at 14:45
Add a ment  | 

2 Answers 2

Reset to default 2

Do not use the if. if statement is executed on page load.

Instead, use Onclick() for example :

var data = "";

function clickBtn() {
  if(data != "")
      document.getElementById("result").innerHTML = "Hello World !";
  else
    getData();
}

function getData() {
    data = "Hello World !";
}
<button onclick="clickBtn()">Click me</button>

<p id="result"></p>

Good question, lets use the an HTML file that references a JavaScript.

So the first file lets call it webpage.html

<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body> 

<input type="button" value="save" onclick="save()"></input>

<input type="button" value="display" onclick="print()"></input>

<div id="area"></div>
</body>
</html>

And the second file script.js

function save()
{

StringTest="Hello world";

}


function print()
{

document.getElementById("area").innerHTML=StringTest;

}

The approach might be a little different but this is remended as you would more control over the elements in the script.

For example: <input type="button" will tell the script that it is a form input of the type button whose click will call the function print() in the JavaScript

document.getElementById("area")captures the elements that we define from the Document Object Model(DOM)

本文标签: buttonclickButton Clicked true or falseJavaScriptStack Overflow