【问题标题】:JS setting attr(value) don't returning in DOMJS 设置 attr(value) 不在 DOM 中返回
【发布时间】:2018-07-23 21:22:58
【问题描述】:

我使用 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') 
  }
});

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

【问题讨论】:

  • 旁注,$('#phone').val(event.data)val() 的setter 版本
  • 我都用过,结果一样
  • 也只是为了确保。当你说“它工作得很好”时,意味着你在聚焦之前看到了输入框中的值?
  • 好吧,根据定义,如果您以编程方式分配输入的值,keyup 事件将不会触发,也不会成为焦点。您可以手动发送一个应该可以工作的焦点/按键事件。
  • 是的,我看到焦点前输入框中的值

标签: javascript jquery dom websocket


【解决方案1】:

如果您使用 Javascript 设置 input 的值,keyupfocus 事件自然不会触发。您需要在input 上使用Javascript 来focus

改变

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>

【讨论】:

    【解决方案2】:

    据我所知,以编程方式设置输入的值不会focus 它,也不会触发keyup 事件来触发。但是,您可以在 WebSocket 发送消息后手动触发focus 事件或keyup 事件。这可能就是你要找的东西;

    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').val(event.data);
           $("#phone").focus(); //we now focus the input which should fire your focus event listener
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 1970-01-01
      相关资源
      最近更新 更多