作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的标题可能并不能真正表达我想要实现的目标,所以我希望读者可以先解决我的问题。我的页面上有许多具有不同 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 allinput
element
event-handler
中的
this
上下文将是元素
,在其上事件
被调用
code> 因此 this.id
将返回 element
的 id
属性或 ""
(空)
$(':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/
我是一名优秀的程序员,十分优秀!