如何从事件处理程序获取jquery选择器 [英] How to get jquery selector from event handler

查看:68
本文介绍了如何从事件处理程序获取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="https://cdnjs.cloudflare.com/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="https://cdnjs.cloudflare.com/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选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆