从HTML调用js函数时是否可以访问javascript变量?

时间:2022-06-25 20:25:09

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?

我正在尝试将Java程序转换为HTML和JS,并且在Java代码中,我使用该类中的int调用方法。这可能与HTML和JS一起使用吗?我可以写onload =“myFunc(i + 1)”或者那样的东西吗?

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

如果需要,Java代码如下所示:

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?

我可以在HTML和JavaScript中做这样的事情吗?

1 个解决方案

#1


1  

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>

#1


1  

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>