Javascript 事件应该触发多次但只触发了一次
Javascript Event should fire multiple times but it fired only once
按钮上的点击事件仅在第一次调用时触发一次,我不知道为什么会这样,我使用的是最新版本的 socket.io、express 和 passport截至 2021 年 11 月 2 日(dd/mm/yy)。
我正在尝试构建一个实时聊天网络应用程序,当用户单击按钮时,它应该在消息框中显示他的消息并应用名为 myMsg(name, body)
的功能,我没有我认为我的发射有问题,因为只有在第一次触发事件时,消息才会成功发送到另一端。
客户端 JS:
const msgbox = (name, body)=>{
const element = `<div class="message-recieved">
<p><strong>${name}</strong></h>
<p>${body}</p></div>`;
document.querySelector(".scroll").insertAdjacentHTML("beforeend", element);
}
const myMsg = (name, body) =>{
const element= `<div class="msg-sent ml-auto">
<p><strong>${name}</strong></p>
<p>${body}</p></div>`;
document.querySelector(".scroll").innerHTML += element;
}
$(".button").click(function(event){
const userId = event.target.value;
const msg = {
userId: userId,
body: document.querySelector(".message").value
};
if(msg.body !== null){
const name = document.querySelector(".active").textContent;
myMsg(name, msg.body);
socket.emit("publicMessage", msg);
}
return false;
});
socket.on("publicMessage", function(msg, name){
msgbox(name, msg.body);
});
应用程序 JS:
io.on('connection', function(socket) {
console.log("Made socket connection");
socket.on("publicMessage", function(msg) {
User.findOne({
_id: msg.userId
}, function(err, found) {
if (found) {
found.messages.push(msg.body)
socket.broadcast.emit("publicMessage", msg, found.fullName);
}
})
});
});
我的HTML:
<form class="">
<div class="input mr-auto ml-auto">
<div class="input-group">
<input class="message" value="" type="text" class="form-control" placeholder="Message" aria-label="Message" aria-describedby="message">
<div class="input-group-append">
<button class="btn btn-outline-primary button" type="button" name="button" value="<%=userId%>" id="button-addon2">Send</button>
</div>
</div>
</div>
</form>
我的 App JS 设置代码:
const express = require("express");
const bodyParser = require("body-parser");
const socket = require('socket.io');
const app = express();
const activeUsers = new Set();
const Users = [];
const ejs = require('ejs');
const mongoose = require("mongoose");
const session = require('express-session')
const passport = require('passport');
const passportLocalMangoose = require("passport-local-mongoose");
app.use(session({secret: process.env.SECRET, resave: false, saveUninitialized: false}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);
mongoose.connect("mongodb://localhost:27017/usersDB");
const userSchema = new mongoose.Schema({fullName: String, email: String, password: String, messages: [String]});
userSchema.plugin(passportLocalMangoose);
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(function(User, done) {
done(null, User.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + "/public"));
const server = app.listen(3000, function(err) {
if (!err) {
console.log("Server is running on port 3000");
} else {
console.log(err);
}
});
const io = socket(server);
感谢@Barmar 和其他在评论中帮助过我的人。
发生此问题是因为每当您在父元素内创建子元素时,都会重新创建该父元素内的所有元素,并且不会设置该父元素内的所有事件侦听器。
详情请看评论
按钮上的点击事件仅在第一次调用时触发一次,我不知道为什么会这样,我使用的是最新版本的 socket.io、express 和 passport截至 2021 年 11 月 2 日(dd/mm/yy)。
我正在尝试构建一个实时聊天网络应用程序,当用户单击按钮时,它应该在消息框中显示他的消息并应用名为 myMsg(name, body)
的功能,我没有我认为我的发射有问题,因为只有在第一次触发事件时,消息才会成功发送到另一端。
客户端 JS:
const msgbox = (name, body)=>{
const element = `<div class="message-recieved">
<p><strong>${name}</strong></h>
<p>${body}</p></div>`;
document.querySelector(".scroll").insertAdjacentHTML("beforeend", element);
}
const myMsg = (name, body) =>{
const element= `<div class="msg-sent ml-auto">
<p><strong>${name}</strong></p>
<p>${body}</p></div>`;
document.querySelector(".scroll").innerHTML += element;
}
$(".button").click(function(event){
const userId = event.target.value;
const msg = {
userId: userId,
body: document.querySelector(".message").value
};
if(msg.body !== null){
const name = document.querySelector(".active").textContent;
myMsg(name, msg.body);
socket.emit("publicMessage", msg);
}
return false;
});
socket.on("publicMessage", function(msg, name){
msgbox(name, msg.body);
});
应用程序 JS:
io.on('connection', function(socket) {
console.log("Made socket connection");
socket.on("publicMessage", function(msg) {
User.findOne({
_id: msg.userId
}, function(err, found) {
if (found) {
found.messages.push(msg.body)
socket.broadcast.emit("publicMessage", msg, found.fullName);
}
})
});
});
我的HTML:
<form class="">
<div class="input mr-auto ml-auto">
<div class="input-group">
<input class="message" value="" type="text" class="form-control" placeholder="Message" aria-label="Message" aria-describedby="message">
<div class="input-group-append">
<button class="btn btn-outline-primary button" type="button" name="button" value="<%=userId%>" id="button-addon2">Send</button>
</div>
</div>
</div>
</form>
我的 App JS 设置代码:
const express = require("express");
const bodyParser = require("body-parser");
const socket = require('socket.io');
const app = express();
const activeUsers = new Set();
const Users = [];
const ejs = require('ejs');
const mongoose = require("mongoose");
const session = require('express-session')
const passport = require('passport');
const passportLocalMangoose = require("passport-local-mongoose");
app.use(session({secret: process.env.SECRET, resave: false, saveUninitialized: false}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);
mongoose.connect("mongodb://localhost:27017/usersDB");
const userSchema = new mongoose.Schema({fullName: String, email: String, password: String, messages: [String]});
userSchema.plugin(passportLocalMangoose);
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(function(User, done) {
done(null, User.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + "/public"));
const server = app.listen(3000, function(err) {
if (!err) {
console.log("Server is running on port 3000");
} else {
console.log(err);
}
});
const io = socket(server);
感谢@Barmar 和其他在评论中帮助过我的人。
发生此问题是因为每当您在父元素内创建子元素时,都会重新创建该父元素内的所有元素,并且不会设置该父元素内的所有事件侦听器。
详情请看评论