简体   繁体   English

单击按钮时 Onclick 不起作用

[英]Onclick not working when I click the button

Reloading the page makes the function work but not when I click the button.重新加载页面使该功能起作用,但当我单击按钮时却不起作用。

    <button onclick="randomPass()">Generate passwords</button>

function randomPass() {
    let password = ""
    for (let i = 0; i < passwordLength; i++) {
        password += generatePass()
    }
    return password
    console.log(password)
}

const pass1 = randomPass()

firstPass.textContent = pass1

but not when I click the button但不是当我点击按钮时

Because the function doesn't really do anything when you click the button.因为当您单击按钮时,该函数实际上并没有做任何事情 The function returns a value, but the button has no way of knowing what you want done with that value.该函数返回一个值,但按钮无法知道您要对该值做什么。

Here you use the returned value:这里使用返回值:

const pass1 = randomPass()

firstPass.textContent = pass1

Here (in the button click) you don't:在这里(在按钮点击中)你没有:

randomPass()

If the intent is for this to all happen on a click event, put all of the logic that you want to happen into the function:如果意图是让这一切都发生在点击事件上,请将您想要发生的所有逻辑放入函数中:

function randomPass() {
    let password = ""
    for (let i = 0; i < passwordLength; i++) {
        password += generatePass()
    }
    console.log(password)
    firstPass.textContent = password
}

Then whether you execute it on a click event or on the page load, it's the same operation:那么无论是在点击事件上执行,还是在页面加载上执行,都是同一个操作:

randomPass()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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