javascript - JS 设置 attr(value) 不在 DOM 中返回
问题描述
我正在使用 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')
}
});
但这在我手动输入文本之前不起作用
解决方案
如果您正在设置input
using Javascript 的值,则keyup
andfocus
事件自然不会触发。您将需要focus
在input
.
改变
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>
推荐阅读
- python - Pandas:提取列值,其中列名与另一列中的行值匹配
- r - 在“优化”R 函数中控制步长
- magento2 - 目录价格规则 Magento 2
- android-intent - Chromebook,意图过滤器从 Android 应用程序上的 gmail 应用程序下载附件
- java - SingleTon 类未同步并返回多个实例
- angular - 将自定义指令应用于表单
- elasticsearch - 对加密数据的模糊搜索
- pytorch - PyTorch Dataloader - 枚举时列表不可调用错误
- linked-list - 在 Dartlang 的链表上实现 Iterable 类?
- javascript - Javascript 单选按钮已选中=true 不起作用