【发布时间】:2020-10-25 00:37:10
【问题描述】:
你好,所以我为我构建的聊天创建了一个房间密码验证,并使用 Bootstrap 的 4 模式向用户显示密码输入。
我正在使用 jQuery 来打开模式,就像 $("#password-validation").modal(); 一样。它工作得很好。但是当你关闭模态框,重新打开它并提交输入后,“如果用户点击回车按钮”里面的代码会执行多次而不是on。
// #room-password-btn is the enter button
$("#room-password-btn").click(function(){
console.log("Execute")
});
一个例子:所以如果你(打开模式按钮并关闭模式)* 3 然后点击你会在控制台中看到的输入按钮:
// first open and close
// second open and close
Execute // third open, enter
Execute
Execute
问题的工作模型:https://codepen.io/PachUp/pen/LYGQozz(尝试关闭它并按回车键,您会看到多条消息而不是一条,关闭的次数越多,您会看到的消息越多。我相信如果我修复那么问题就解决了)。
模态:
<div class="modal fade" id="password-validation" tabindex="-1" role="dialog" aria-labelledby="room-password-val-aria" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header text-center">
<h4 class="modal-title w-100 font-weight-bold">Enter the room password</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body mx-3">
<div class="md-form mb-5">
<label data-error="wrong" data-success="right">Room password</label>
<input class="form-control" id="room-password-val">
</div>
</div>
<div class="modal-footer d-flex justify-content-center">
<button class="btn btn-default" id="room-password-btn">Enter</button>
</div>
</div>
</div>
</div>
完整的 JS:
corrent_pass = false;
room_pass = ""
$.ajax({
type: "POST",
url: "/validate",
data: new_room,
success: function(pass){
room_pass = pass; // pass is the room password
}
});
console.log("room pass: " + room_pass)
console.log(room_pass.length)
if(room_pass != "False"){
$("#password-validation").modal('toggle');
$('#password-validation').on('shown.bs.modal', function () {
$('#room-password-val').trigger('focus');
$("#room-password-btn").mousedown(function(){
console.log("Execute")
user_password = $("#room-password-val").val()
console.log(user_password)
console.log(room_pass)
if(user_password == room_pass){
corrent_pass = false
$("#messages").html("");
$("#password-validation .close").click()
toastr["success"]("Entering you into the room!", "Corrent password")
console.log("Joining a room")
socket.emit('leave', {"room" : room})
socket.emit("join", {"room" : new_room})
room = new_room
}
else{
toastr["error"]("Sorry, you have entered the wrong password. Try again.", "Wrong password")
}
});
});
}
else{
console.log("no password")
$("#messages").html("");
console.log("Joining a room")
socket.emit('leave', {"room" : room})
socket.emit("join", {"room" : new_room})
var room_msg = "You have joined " + new_room
toastr["success"](room_msg, "Room joined")
room = new_room
}
}
【问题讨论】:
-
您能分享一下您目前工作的代码吗?
-
@ShahnawazHossan 我做到了。我不想分享它,因为我认为 js 代码的整个部分(与问题相关)是相关的,但如果它对你有帮助
标签: javascript jquery bootstrap-4 modal-dialog bootstrap-modal