我使用 WebSocketd 发送数据并从 STDOUT 检索数据,然后使用 JS 访问消息:
var ws = new WebSocket('ws://ip-address:8081/');
ws.onopen = function() {
document.getElementById("phone").style.background= '#cfc';
};
ws.onclose = function() {
document.getElementById("phone").style.background= '#fcc';
};
ws.onmessage = function(event) {
$('#phone').attr('value', event.data);
};
它工作得很好,然后我尝试了以下方法来测试设置websocket连接后#phone的值是否会改变
var max = 10;
$('#phone').focus(function(e)
{
if ($(this).val().length > max)
{ alert('action fired')
}
})
.keyup(function(e){
if ($(this).val().length > max) {
alert('action fired')
}
});
但这只有在我手动输入文本后才会起作用
最佳答案
如果您使用 Javascript 设置 input
的值,则 keyup
和 focus
事件自然不会触发。您需要使用 Javascript 将焦点
放在输入
上。
改变
ws.onmessage = function(event) {
$('#phone').attr('value', event.data);
};
至
ws.onmessage = function(event) {
$('#phone').attr('value', event.data);
$('#phone').focus();
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="phone"/>
<p/>
<textarea id="message">
</textarea>
<br/>
<button id="sendMessage">Send</button>
<script>
var max = 10;
$('#sendMessage').click(function(e){
//simulating a sent message
$('#phone').attr('value', $('#message').val());
$('#phone').focus();
});
$('#message').keypress(function(e){
if(e.keyCode==13){
//simulating a sent message
$('#phone').attr('value', $('#message').val());
$('#phone').focus();
}
});
$('#phone').focus(function(e)
{
if ($(this).val().length > max)
{ console.log('action fired')
}
})
.keyup(function(e){
if ($(this).val().length > max) {
console.log('action fired')
}
});
</script>
关于javascript - JS 设置 attr(value) 不会在 DOM 中返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51487392/