如何从事件处理程序获取jquery选择器

编程入门 行业动态 更新时间:2024-10-28 08:20:26
本文介绍了如何从事件处理程序获取jquery选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在页面上有几个输入元素,其中一个(第一个)是我可以输入其他任何元素的特定ID的地方.

I have several input elements on a page and one of them (the first one) is where I can enter in a specific id of any of the other elements.

我希望我的代码以这样一种方式设置:当我关注其他任何元素,并且其id与在第一个元素中输入的文本匹配时,该文本将突出显示,并且指示我选择了正确元素的文本是显示在其中.

I want my code set up in such a way that when i focus on any of the other elements and its id matches the text that was entered in the first element, it is highlighted and a text indicating i selected the correct element is displayed within it.

我使用在第一个输入元素中输入的文本来形成我要查找的ID.

I use the text entered in the first input element to form the id that I am looking for.

到目前为止,这就是我所拥有的.

So far this is what i have.

$(document).ready(function() {     var selector;      $('#selector').on('input', function() {         selector = $(this).val();     });     $('#' + selector).on('focus', function() { if ($(this).is('#' + selector)) {         $(this).val("that's me: " + selector).css('border', 'solid red 1px'); }     }).on('blur', function() { $(this).val('').css('border', 'solid #555 1px'); }); });

<script src="cdnjs.cloudflare/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id='selector' type='text' /><br /> <input id='target1' type='text' /><br /> <input id='target2' type='text' /><br /> <input id='target3' type='text' /><br />

在第一个输入中输入任何目标输入元素的ID之后,设置选择器"值.但是,我的焦点处理程序似乎未针对其他任何输入元素触发,并且控制台上未报告任何错误.可能是什么问题.

After entering the id of anyone of the target input elements in the first input, I set the "selector" value. However, my focus handler seems not to be firing for any of the other input elements and no error is reported on the console. What could be the problem.

推荐答案

不是使用$('#' +selector),而是使用$('input[id^=target]')(或添加一个通用类),而您的其他逻辑保持不变

Instead of using $('#' +selector) use $('input[id^=target]') (or add a common class) and your other logic remains the same

$(document).ready(function() {     var selector;      $('#selector').on('input', function() {         selector = $(this).val();     });     $('input[id^=target]').on('focus', function() { if ($(this).is('#' + selector)) {         $(this).val("that's me: " + selector).css('border', 'solid red 1px'); }     }).on('blur', function() { $(this).val('').css('border', 'solid #555 1px'); }); });

<script src="cdnjs.cloudflare/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id='selector' type='text' /><br /> <input id='target1' type='text' /><br /> <input id='target2' type='text' /><br /> <input id='target3' type='text' /><br />

更多推荐

如何从事件处理程序获取jquery选择器

本文发布于:2023-11-11 13:38:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1578596.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   程序   选择器   jquery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!