简体   繁体   中英

Is it possible to access a javascript variable when calling a js function from HTML?

I am trying to convert a Java program into HTML and JS, and in the Java code I call a method using an int from that class. Is this possible with HTML and JS? Can I write onload="myFunc(i + 1)" or something to that effect?

If you need it, the Java code looks like this:

public int i = 0;

public String chooseACard(int j) {
    if(j > cards.length - 1) j = 0;
    return cards[j].front;
}

and it is called by:

ActionListener changeFrontListener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == nextCard) {
                textBox.setText(vc.chooseACard(vc.i + 1));
                if(vc.i + 1 > vc.cards.length - 1) vc.i = 0;
                else vc.i++;
            }
        }

    };

Can I do anything like this in HTML and JavaScript?

Yes, you can do it like shown below. Basically, You can assign the handler of the event a function name or a function expression.

 var i = 9; function myFunc(t){ console.log(t);} 
 <button id="button1" onclick="myFunc(i + 1);">TestMe</button> 

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