gpt4 book ai didi

javascript - 似乎无法更改 span 元素的类

转载 作者:行者123 更新时间:2023-12-03 00:24:00 25 4
gpt4 key购买 nike

我正在实现一项功能,当单击字段右侧的眼睛图标时,可以显示密码字段的内容。单击该项目时,应该发生 2 件事:1. 密码字段应成为文本字段2. 眼睛的图标应该变成斜眼3. 当您再次单击该图标时,反之亦然。

我使用 Bootstrap 4.0 和 Font Awesome 进行总体设计和图标。我当前的代码更改了密码字段的类型,但未更改按钮上的图标。

有什么想法吗?

HTML 部分:

<div class="form-group">
<label for="password">Passwort</label>
<div class="input-group" id="show_hide_password">
<input type="password" id="password" class="form-control" name="password" placeholder="Leer lassen wenn das Passwort nicht ge&auml;ndert werden soll.">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="eyeButton" data-action="showPW"><span id="eyeLogo" class="far fa-eye"></span></button>
</div>
</div>
</div>

Javascript 部分:

var theeyeButton = document.querySelector("[data-action=showPW]");
var theeyeLogo = document.querySelector("#eyeLogo");
var pwField = document.querySelector("#password");
//var theeyeButton = document.getElementById("showPW");
if (theeyeButton) {
theeyeButton.addEventListener("click", function (event) {
if(pwField.type == "text"){
pwField.type = "password";
theeyeLogo.className = "far fa-eye";
}
else if(pwField.type == "password"){
pwField.type = "text";
theeyeLogo.className = "far fa-eye-slash";
}
});
}

最佳答案

这样就可以了

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="form-group">
<label for="password">Passwort</label>
<div class="input-group" id="show_hide_password">
<input type="password" id="password" class="form-control" name="password" placeholder="Leer lassen wenn das Passwort nicht ge&auml;ndert werden soll.">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="eyeButton" data-action="showPW" value="button">button<span id="eyeLogo" class="far fa-eye-slash"></span></button>
</div>
</div>
</div>
<script>
var theeyeButton = document.querySelector("[data-action=showPW]");
var theeyeLogo = document.querySelector("#eyeLogo");
var pwField = document.querySelector("#password");
//var theeyeButton = document.getElementById("showPW");
if (theeyeButton) {
theeyeButton.addEventListener("click", function (event) {
if(pwField.type == "text"){
pwField.type = "password";
theeyeLogo.className = "far fa-eye-slash";
}
else if(pwField.type == "password"){
pwField.type = "text";
theeyeLogo.className = "far fa-eye";
}
});
}
</script>
</body>
</html>

关于javascript - 似乎无法更改 span 元素的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54168913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com