【问题标题】:how do I get $(this),val() in the function?如何在函数中获取 $(this),val() ?
【发布时间】:2022-11-20 03:53:24
【问题描述】:

我在 onfocus 事件中有一个输入,当触发时,将调用 getValue() 函数,在该函数中我尝试在它处于焦点时获取该输入的值

input:
<input type="text" onfocus="getValue()" name="title" id="title" class=" form__control" value="<?=$row_title['TITLE'] ?>">
}
fuction:
function getValue() {
  before_value = $(this).val();
  console.log(before_value);
}

不幸的是,执行我的代码时出现此错误:

jquery.min.js:2 未捕获类型错误:无法读取未定义的属性(读取“toLowerCase”)

【问题讨论】:

  • 在您显示的代码中没有调用toLowerCase(),因此,错误不是来自该代码段......
  • 我根本不在项目的任何地方使用这样的功能
  • 当我删除 $(this).val() 并写入 console.log("hello") - 一切正常
  • 您必须显式设置 this-context:onfocus="getValue.call(this)" 否则 this(在您的 getValue 函数中)将指向全局 window 对象。
  • 这没有定义。你必须研究它是如何工作的或使用 function.call / function.apply 来解决你的问题

标签: javascript html


【解决方案1】:

function getValue() {
  before_value = $(this).val();
  console.log(before_value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" onfocus="getValue.call(this)" name="title" id="title" class=" form__control" value="<?=$row_title['TITLE'] ?>">

【讨论】:

  • 我不需要 id,那时我不会问这样的问题。我需要 $(this),作为一种通用方法,因为在项目中我进一步添加块和 id 更改,我需要获取输入专注于它时的价值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多