我一直在搜索渲染html页面时javascript代码会发生什么。
在我的html页面中,我有一些脚本可以说(做)两件事。一种是打开Node.js
服务器的套接字并监听事件用户列表,另一项任务是注册按钮点击事件。
首先,我尝试过这样:
var socket = io.connect(window.location.href);
socket.on("user-list", (data) => {
console.log("On no problem: " + JSON.stringify(data))
let str = "";
for(let i = 0; i < data.length; i++) {
str += "Name: " + data[i].name + " Age: " + data[i].age + " | ";
}
$("#private").text(str)
})
$("#submit-btn").click(function() {
let userName = $("#username").val(),
age = $("#age").val();
if( isNaN(age) ){
console.log("Age is NaN")
alert("Age must be a number!")
return;
}
$.post("user-data", {username: userName, age: age}, function(result) {
console.log(result);
})
})
但点击时按钮不起作用。虽然,套接字连接运行良好。
然后我尝试在$(document).ready(function() {...})
中包含按钮点击事件注册。像这样:
var socket = io.connect(window.location.href);
socket.on("user-list", (data) => {
console.log("On no problem: " + JSON.stringify(data))
let str = "";
for(let i = 0; i < data.length; i++) {
str += "Name: " + data[i].name + " Age: " + data[i].age + " | ";
}
$("#private").text(str)
})
$(document).ready(function() {
$("#submit-btn").click(function() {
let userName = $("#username").val(),
age = $("#age").val();
if( isNaN(age) ){
console.log("Age is NaN")
alert("Age must be a number!")
return;
}
$.post("user-data", {username: userName, age: age}, function(result) {
console.log(result);
})
})
})
现在它有效。我知道文档加载时会引发$(document).ready(function()
,但为什么没有该函数它会工作?
另一个问题是:为什么socket
仍然有效,但未被$(document).ready(function()
包裹?
换句话说,为什么$("#submit-btn").click(function()....
需要$(document).ready(function().....
才能工作?
答案 0 :(得分:0)
Javascript会在浏览器在HTML页面中发现它的第二步执行。所以当你的浏览器发现代码时,你的套接字连接就会被初始化。但是,按钮需要一个html对象(按钮标签)才能进行初始化。如果您的javscript代码位于页面的head-section中,那么脚本很可能无法执行该按钮。解决这个问题。你可以将你的javascript移到页面底部。