Cannot read property 'substring' of undefined?

`<html>
<script src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">

input_1 = $('#test')
function test(){
    
    input_1.selectionStart = 0;
    input_1.selectionEnd = 2;
    var selection = input_1.val().substring(input_1.selectionStart,input_1.selectionEnd);
    alert(selection)
}
function location_gb(){
    input_1.selectionStart = 5;   //选中区域左边界
    input_1.selectionEnd = 5;
}
</script>

<body>

<input type="button" value="登录" onclick="test()">        
<input  id="test" >

</body>

</html>`

阅读 5.4k
2 个回答

典型的加载顺序问题。

HTML 是从上至下顺序加载的,你的 <script> 标签写在 <body> 前面,当加载到 <script> 的时候,压根还没有 #test 这么个 DOM 呢。

要么把 <script> 放在最下面,让 <body> 先加载;要么给你的代码套在 window.onload = function() {}$(document).ready(function() { }) 回调里。


function test(){
    var input_1 = $('#test')
    input_1.selectionStart = 0;
    input_1.selectionEnd = 2;
    var selection = input_1.val().substring(input_1.selectionStart,input_1.selectionEnd);
    alert(selection)
}
function location_gb(){
    var input_1 = $('#test')
    input_1.selectionStart = 5;   //选中区域左边界
    input_1.selectionEnd = 5;
}

触发事件的时候再去获取元素

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题