【问题标题】:How to add some default text to a input text field on button click using jQuery如何使用jQuery在按钮单击时向输入文本字段添加一些默认文本
【发布时间】:2013-12-14 22:11:44
【问题描述】:

让我有以下表单域。

<input tyep="text" id="text_field_one" name="your_name"/>

<input tyep="text" id="text_field_two" name="your_friends_name"/>

<input tyep="text" id="text_field_three" name="your_girl_friends_name"/>

<input type="button" id="addToText" value="Add your Default text"/>

现在,当我单击按钮时,我想添加一些默认文本,例如使用 jQuery 的“Hello”。

但默认文本应该只添加到我上次使用的文本字段中。我无法使用focused,因为我的鼠标专注于按钮本身。

为了让我的问题更清楚,下面是一个例子:

让我输入第二个文本字段,我写了“Paul”。让我要添加的默认文本是“你好吗?”因此,在我单击按钮后,我的第二个文本字段内容应该是“Paul 你好吗?”但目前第一个和第三个文本字段不应更改。

是否可以通过这种方式进行跟踪。或者我应该换一种方式思考。我需要你的建议和帮助。

【问题讨论】:

    标签: jquery html text input focus


    【解决方案1】:

    只需将任何类型的最后一个焦点元素存储在变量中

    var last = null;
    
    $('input[type="text"]').on('focus', function() {
        last = this;
    });
    
    $('#addToText').on('click', function() {
        if (last) $(last).val('Hello');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      相关资源
      最近更新 更多