【问题标题】:how to get text from a span of a input field when it gains focus?获得焦点时如何从输入字段的范围中获取文本?
【发布时间】:2023-03-22 02:31:01
【问题描述】:

如何从文本输入之前的跨度中获取文本,以及当该输入获得焦点时获取焦点输入的跨度?假设输入是这样的:

<div>
<label for="id">...</label>
<input type="text" id="id" value="" />
<span class="span">span</span>
</div>

有没有办法获得价值可能是这样的:

$('#id').live('focus', function(){
var text = $(this, '.span').text();
});

我进行实时绑定,因为输入是动态创建的 我也尝试过类似的方法,但似乎不起作用:

var text = $(this).find('.span').text();

提前谢谢你!

【问题讨论】:

    标签: jquery text input this html


    【解决方案1】:

    您是指成功您输入的跨度?这就是你的 html 的结构。

    我想这就是你要找的东西

    $('#id').live('focus', function(){
       var text = $(this).siblings("span:first").text();
    });
    

    或者,如果您 100% 确定跨度将始终紧邻输入,您可以这样做

    $('#id').live('focus', function(){
       var text = $(this).next().text();
    });
    

    但如果您确实想要输入之前的跨度,您可以使用prev 函数:

    $('#id').live('focus', function(){
       var text = $(this).prev("span").text();
    });
    

    最后,请注意 live 已弃用。通常我会建议切换到on,但由于您只是通过 id 选择单个元素,为什么不简单地这样做:

    $('#id').focus(function() {
       var text = $(this).prev("span").text();
    });
    

    或者让它更通用,并且能够与任何输入一起工作

    $(document).on("focus", "input[type='text']", function() {
       var text = $(this).prev("span").text();
    });
    

    【讨论】:

      【解决方案2】:

      如果你知道span是下一个元素:

      $('#id').live('focus', function(){
         var text = $(this).next().text();
      });
      

      也无需将课程span 分配给您的跨度。

      【讨论】:

        【解决方案3】:

        试试

        $('#id').live('click', function(){
           var text = $(this).siblings('span').text();
           alert(text);
        });
        

        DEMO //这里用click,你可以改成focus

        .siblings()

        【讨论】:

          猜你喜欢
          • 2011-04-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-02
          • 1970-01-01
          相关资源
          最近更新 更多