我想将表单中的username
输入传递给socket.emit
params
。但是,当我进入socket.on function
时,userName
未定义。它应该是范围问题,而我不知道如何解决这个问题。
我省略了一些代码来简化问题。没有必要让代码可运行,我只是想让方法如何处理这个问题。
$("button").click(function (event) {
event.preventDefault();
setUserName($("input[name=name]").val());
});
var userName;
function setUserName(userName2) {
userName=userName2;
}
var socket = io();
socket.on('connect', function () {
var params = {
name:userName
}
socket.emit('join', params, function (err) {
});
});

<body class="centered-form">
<div class="centered-form__form">
<form>
<div class="form-field">
<label>Display name</label>
<input type="text" name="name" autofocus/>
</div>
<div class="form-field">
<button id="submit">Submit</button>
</div>
</form>
</div>
</body>
<script src="/libs/jquery-3.1.0.min.js"></script>
<script src="/chat.js"></script>
&#13;
答案 0 :(得分:0)
您遇到了userName
的范围问题
$("button").click(function (event) {
event.preventDefault();
setUserName($("input[name=name]").val());
});
var userName;
function setUserName(userName) {
//this refers to the scope of the function
this.userName=userName;
}
var socket = io();
socket.on('connect', function () {
var params = {
//this refers to the scope of the socket
name:this.userName
}
socket.emit('join', params, function (err) {
});
});
&#13;
尝试
$("button").click(function (event) {
console.log('__BUTTON_EVENT__');
event.preventDefault();
let name = $("input[name=name]").val();
console.log('__USER_NAME__: ', name);
setUserName(name);
});
var userName;
function setUserName(name) {
userName = name;
}
var socket = io();
socket.on('connect', function () {
var params = {
name:userName
}
console.log('__CONNECTING__: ', params.name);
socket.emit('join', params, function (err) {
});
});
&#13;