gpt4 book ai didi

javascript - 如何在javascript中获取焦点元素的Id

转载 作者:行者123 更新时间:2023-12-02 14:26:50 26 4
gpt4 key购买 nike

我的标题可能并不能真正表达我想要实现的目标,所以我希望读者可以先解决我的问题。我的页面上有许多具有不同 id 的输入,我想获取获得用户焦点的特定输入的 ID,并在该输入失去焦点时触发事件。我可以通过显式声明 ID 并将 onblur 事件处理程序附加到它来实现此目的,但这将导致编写大量代码,因为我在同一页面上有太多输入。现在我有下面的代码

var \$Title = $('#draft-product_title')
\$Title.on('blur',function(event){
eventId = event.target.id;
draftEventHandler(\$Title,eventId);
});

这是我的输入之一,我有超过 30 个输入,所以我必须复制它 30 次,这太疯狂了,我需要一种方法让它如此灵活,我也尝试过这个,但没有运气

var \$selectorId;
$('body').on('click',function(event) {
\$focusElementId = document.activeElement.id;
\$selectorId = ('#'+\$focusElementId)
console.log(\$selectorId);
});

\$selectorId.on('blur',function(event){
eventId = event.target.id;
draftEventHandler(\$selectorId,eventId);
});

但是此代码错误选择器 ID 未定义,而是定义了 console.log()关于如何实现这项工作的任何帮助,我也对任何其他想法持开放态度,谢谢

最佳答案

Use :input selector to select all input element

event-handler 中的

this 上下文将是元素,在其上事件调用 code> 因此 this.id 将返回 elementid 属性或 ""(空)

$(':input').on('focus', function() {
console.log(this.id);
}).on('blur', function() {
console.log(this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form action="action_page.php">
First name:
<br>
<input type="text" id="name" value="Mickey">
<br>Last name:
<br>
<input type="text" name="lastname" id="lastname" value="Mouse">
<br>
<br>
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="submit" value="Submit">
</form>

关于javascript - 如何在javascript中获取焦点元素的Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38172082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com