Javascript 使用jQuery在输入文本内设置光标

Javascript 使用jQuery在输入文本内设置光标,javascript,jquery,html,input-field,Javascript,Jquery,Html,Input Field,使用此主题: 我编写了此代码,但它不起作用: <input id="myTextInput" type="text" value="some text2"> <input type="button" value="set mouse" id="btn" /> 以及: 我的错在哪里? 谢谢您的错误是选择了jQuery对象而不是DOM元素:replace var inp=$'myTextInput';使用var inp=$'myTextInput'[0] 但是,我建议使用

使用此主题:

我编写了此代码,但它不起作用:

<input id="myTextInput" type="text" value="some text2">
<input type="button" value="set mouse" id="btn" />
以及:

我的错在哪里?
谢谢

您的错误是选择了jQuery对象而不是DOM元素:replace var inp=$'myTextInput';使用var inp=$'myTextInput'[0]

但是,我建议使用来自的插件,因为代码看起来更干净:

$.fn.selectRange=函数开始、结束{ 返回this.eachfunction{ 如果此选项为.setSelectionRange{ 这是重点; 此.setSelectionRangestart,end; }否则,如果此.createTextRange{ var range=this.createTextRange; range.collapsetrue; 范围。移动结束‘字符’,结束; range.moveStart'character',start; range.select; } }; }; $document.readyfunction{ $'btn'。单击,函数{ var-pos=7; $'myTextInput'.focus.selectRangepos,pos; }; };
要使用setSelectionRange或createTextRange,需要DOM元素而不是JQuery对象。 使用.get0检索它

var inp = $('#myTextInput');
inp.focus();
inp = inp.get(0);
正确的搜索词是插入符号
var inp = $('#myTextInput');
inp.focus();
inp = inp.get(0);