嗨,我试图获取输入的选定值,当输入以Tab键为焦点时。这是我的代码
HTML,
<input id='texteb' type="text" value=''/>
<button>
click
</button>
JS
$(function(){
$(window).on('keyup', function (e) {
var focused = $(':focus');
if (e.which === 9){
var text = focused;
var t = text.value.substring(text.selectionStart, text.selectionEnd - text.selectionStart);
alert(t);
}
});
});
但是我得到这个错误,
TypeError:text.value未定义
这是Jsfiddle。
有了答案,这个问题可以用.val()解决,但是selectionStart似乎给出了undef
最佳答案
我看着你在摆弄第6行:jsfiddle - modified
//var text = focused;
var text = focused[0];
得到
undefined
的原因是,您正在获取不具有那些属性(value
,selectionStart
等)的jQuery对象(即“聚焦”)。但是,您真正需要的是javascript对象,可通过focused[0]
使用。有关更多方法,请检查以下内容:
How do I pull a native DOM element from a jQuery object?(来自:https://learn.jquery.com/)
(ps。我想知道您在使用这段代码做什么?)
关于javascript - TypeError:text.value未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56724226/