移动端Chrome/Samsung Internet获取input值为空的原因及解决办法
移动端浏览器获取输入框值为空的修复方案
问题场景
桌面端Chrome浏览器中,代码可正常获取输入框#iosm的值;但在安卓Chrome或Samsung Internet浏览器中,当#chw输入框输入值并触发blur事件后,获取#iosm的值返回空(即使#iosm已输入内容)。额外测试显示:blur当前输入框时弹窗能显示自身正确值,但切换到另一输入框触发blur后,再获取之前输入框的值就为空,清理缓存无效。
原代码
JavaScript
document.addEventListener("DOMContentLoaded", function() { jQuery(document).ready(function($) { $('input#chw').on('blur', function() { if ($(this).val() && parseInt($(this).val()) > 0) { alert($('input#iosm').val()); // 移动端此处返回空值! } }) }); })
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <form id="send_cmsg"> <table class="main_tab gener_tab"> <tbody> <tr class="gt3c"> <td class="first">Put any numeric value to this input</td> <td class="scnd"><input type="tel" id="iosm" value="" /></td> </tr> <tr class="chw gt3c"> <td class="first">Then put some value here and blur input<br>On Deskop it returns value... on Mobile Devices in return empty value</td> <td class="scnd onnrr"><input id="chw" type="tel" data-nl="een kind" data-nl2="kinderen" data-en="one child" data-en2="children" /></td> </tr> </tbody> </table> </form>
修复方案
方案1:改用原生JS直接获取值
移动端浏览器对原生JS的输入框值获取支持更稳定,绕开老版本jQuery的兼容性问题:
document.addEventListener("DOMContentLoaded", function() { const iosmInput = document.getElementById('iosm'); const chwInput = document.getElementById('chw'); chwInput.addEventListener('blur', function() { const chwVal = this.value; if (chwVal && parseInt(chwVal) > 0) { alert(iosmInput.value); } }); })
方案2:实时同步输入框值到变量
监听input事件实时保存#iosm的值,避免blur时直接获取可能的延迟问题:
document.addEventListener("DOMContentLoaded", function() { jQuery(document).ready(function($) { let iosmValue = ''; $('input#iosm').on('input', function() { iosmValue = $(this).val(); }); $('input#chw').on('blur', function() { if ($(this).val() && parseInt($(this).val()) > 0) { alert(iosmValue); } }) }); })
方案3:替换blur事件为focusout
部分移动端浏览器对blur事件的触发时机存在延迟,改用focusout事件(支持冒泡,触发更稳定):
document.addEventListener("DOMContentLoaded", function() { jQuery(document).ready(function($) { $('input#chw').on('focusout', function() { if ($(this).val() && parseInt($(this).val()) > 0) { alert($('input#iosm').val()); } }) }); })
额外建议
如果继续使用jQuery,建议升级到3.x版本,老版本(如1.9.1)在移动端的输入框处理存在较多兼容性问题。
内容的提问来源于stack exchange,提问作者kibus90
相关产品推荐
相关产品推荐

