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

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

or something like that?

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 gets called:

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 something like this in HTML and JavaScript?

+3


source to share


1 answer


Yes, you can do it as shown below. Basically, you can assign a function name or a function expression to an event handler.



var i = 9;

function myFunc(t){
console.log(t);}
      

<button id="button1" onclick="myFunc(i + 1);">TestMe</button>
      

Run codeHide result


+1


source







All Articles