首页 > 解决方案 > 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') 
  }
});

但这在我手动输入文本之前不起作用

标签: javascriptjquerydomwebsocket

解决方案


如果您正在设置inputusing Javascript 的值,则keyupandfocus事件自然不会触发。您将需要focusinput.

改变

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>


推荐阅读