`<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>`
典型的加载顺序问题。
HTML 是从上至下顺序加载的,你的 <script> 标签写在 <body> 前面,当加载到 <script> 的时候,压根还没有
#test
这么个 DOM 呢。要么把 <script> 放在最下面,让 <body> 先加载;要么给你的代码套在
window.onload = function() {}
或$(document).ready(function() { })
回调里。