简体   繁体   中英

I want to call javascript class from html button on Click event how to do that?

HTML code

As you can this how to call the class method from HTML

<body>
    <input type="text" id="userName">
    <button onclick="st.show()">Click</button>
</body>
<script src="script.js"></script>

I want to display the username in console

Javascript code

class Student{
    constructor(name){
        this.name=name;
    }

    show(){
        console.log(this.name)
    }
}
let name=document.getElementById('userName').value;
var st=new Student(name); 
    

Try the below code. name should be set as " this.name = name ". and show function should log this.name instead of this.username .

class Student {
  constructor(name) {
    this.name = name;
  }

  show() {
    console.log(this.name);
  }
}

Add the below function.

function show() {
  let name = document.getElementById("userName").value;
  var st = new Student(name);
  st.show();
}

Call show() function on button click instead of emp.show()

<body>
    <input type="text" id="userName">
    <button onclick="show()">Click</button>
</body>
<script src="script.js"></script>

You are seeing the variable name with a property?

constructor(name){
    name=this.name;  <-- you have this reversed
}

You are referencing a property you never set

show(){
    console.log(this.username) <-- what is username?
}

}

You are reading the value when the page loads

let name=document.getElementById('userName').value;

Basic idea using getter and setter

 class Student { _name = "unknown" constructor() { } set name(name) { this._name = name } get name() { return this._name } reverseName() { return [...this._name].reverse().join(""); } } const st = new Student(); document.getElementById("userName").addEventListener("input", function (e) { st.name = e.target.value; }); document.getElementById("show").addEventListener("click", function (e) { console.log(st.name); }); document.getElementById("rev").addEventListener("click", function (e) { console.log(st.reverseName()); });
 <label for="username">Name:</label> <input type="text" id="userName"> <button type="button" id="show">Click</button> <button type="button" id="rev">Reverse</button>

Please check if this helps:

 class Student{ constructor(name){ this.name=name; } show(){ console.log(this.name); } } function empShow(){ let name = document.getElementById('userName').value; var st = new Student(name); return st.show(); }
 <body> <input type="text" id="userName"> <button onclick="empShow()">Click</button> </body> <script src="script.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM