如何在onfocus触发的getValue函数中获取$(this).val()?出现类型错误
解决input onfocus事件中$(this)获取值报错的问题
你这段代码报错的核心问题是:内联事件onfocus="getValue()"调用函数时,函数里的this指向的是window对象,而非触发事件的input元素。jQuery的$(this)包装window后调用.val()方法时,由于window不是表单控件,内部执行逻辑会尝试读取不存在的属性,从而抛出Cannot read properties of undefined (reading 'toLowerCase')错误。
以下是几种可行的修复方案:
方案一:调用函数时传入当前元素
修改HTML的内联事件,将this作为参数传递给getValue:<input type="text" onfocus="getValue(this)" name="title" id="title" class=" form__control" value="<?=$row_title['TITLE'] ?>">同步修改JavaScript函数,接收元素参数:
function getValue(element) { const before_value = $(element).val(); console.log(before_value); }方案二:改用jQuery绑定事件(更推荐,实现HTML与JS逻辑分离)
先移除HTML中的onfocus属性:<input type="text" name="title" id="title" class=" form__control" value="<?=$row_title['TITLE'] ?>">再用jQuery的事件绑定方式,此时函数内的
this会正确指向触发事件的input元素:$(function() { $('#title').on('focus', function() { const before_value = $(this).val(); console.log(before_value); }); });方案三:不用jQuery,原生JS直接取值
如果不需要依赖jQuery,也可以用原生方式实现:
HTML修改为:<input type="text" onfocus="getValue(this)" name="title" id="title" class=" form__control" value="<?=$row_title['TITLE'] ?>">JS函数调整为:
function getValue(element) { const before_value = element.value; console.log(before_value); }
内容的提问来源于stack exchange,提问作者Zaskar_6352392
相关产品推荐
相关产品推荐

