不确定在这里问什么,所以请耐心等待。
我有一个输入字段,我需要获取onfocusin和onfocusout事件并执行一些逻辑。
我想使用一个通用函数来处理onfocusin,并使用一个通用函数来处理onfocusout函数。
那么-我将如何确定函数中输入字段的ID?
<input type="text" class="form-control" id="location_notes" onfocusin="fieldFocusIn()" onfocusout="fieldFocusOut()" placeholder="Location Notes">
<input type="text" class="form-control" id="additional_notes" onfocusin="fieldFocusIn()" onfocusout="fieldFocusOut()" placeholder="Additional Notes">
function fieldFocusIn(){
// do some stuff with the calling field
}
function fieldFocusOut(){
// do some different stuff with the calling field
}
答案 0 :(得分:2)
使用event.currentTarget.id
-为了获取事件对象,因为您正在使用内联事件,所以需要将单词event
传递到函数调用中。 a.e. onfocusin="fieldFocusIn(event)"
在事件处理程序中,您将收到event参数,并查看该事件内的currentTarget
对象以及该对象的id
属性。
<input type="text" class="form-control" id="location_notes" onfocusin="fieldFocusIn(event)" onfocusout="fieldFocusOut(event)" placeholder="Location Notes">
<input type="text" class="form-control" id="additional_notes" onfocusin="fieldFocusIn(event)" onfocusout="fieldFocusOut(event)" placeholder="Additional Notes">
<script>
function fieldFocusIn(e){
console.log(e.currentTarget.id);
// do some stuff with the calling field
}
function fieldFocusOut(e){
console.log(e.currentTarget.id);
// do some different stuff with the calling field
}
</script>
答案 1 :(得分:1)
您可以简单地将所需的<input
id="location_notes"
onfocusin="fieldFocusIn('location_notes')"
onfocusout="fieldFocusOut('location_notes')"
>
function fieldFocusIn(id){
console.log(id) // location_notes
}
function fieldFocusOut(id){
console.log(id) // location_notes
}
作为函数参数传递:
.material-icons.md-10 {
font-size: 10px;
width: 10px;
height: 10px;
line-height: 10px;
}
答案 2 :(得分:0)
在以下情况下,只需从id
中提取target
:
function fieldFocusIn(event){
console.log(event.target.attributes.id.value);
}
function fieldFocusOut(event){
console.log(event.target.attributes.id.value);
}
答案 3 :(得分:0)
如果发现自己一次又一次地附加相同的事件处理程序,也可以考虑使用event delegation:
password
function focusIn(callback) {
document.querySelector('#fields').addEventListener('focusin',
(event) => callback(event.target.id));
}
function focusOut(callback) {
document.querySelector('#fields').addEventListener('focusout',
(event) => callback(event.target.id));
}
focusIn((id) => console.log(`focus in: ${id}`));
focusOut((id) => console.log(`focus out: ${id}`));