【问题标题】:jQuery: Last focused input field not populating as expectedjQuery:最后一个焦点输入字段未按预期填充
【发布时间】:2014-05-29 14:26:26
【问题描述】:

我有一个变量列表和一个字段列表,其中可能包含文本输入或文本区域。我想单击一个变量名称并让它自动附加到最后一个焦点输入/文本区域字段中的内容末尾(假设最后一个焦点是这些字段之一)。

这是一个 JsFiddle,它说明了我正在尝试做的事情:http://jsfiddle.net/fyUn6/

HTML:

Field 1: <input type="text" name="field[1]" /><br/>
Field 2: <input type="text" name="field[2]" /><br/>
Field 3: <input type="text" name="field[3]" /><br/>
Field 4: <textarea name="field[4]"></textarea><br/>
Field 5: <textarea name="field[5]"></textarea><br/>
<br/>
<span class="variable">NAME</span><br/>
<span class="variable">AGE</span><br/>
<span class="variable">WEIGHT</span><br/>

JavaScript:

jQuery(document).ready(function() {
    var prevFocus;

    jQuery("input[type=text], textarea").focus(function() {
        prevFocus = jQuery(this);
    });

    jQuery(".variable").click(function() {
        if(typeof prevFocus !== "undefined") {
            prevFocus.html(prevFocus.html()+jQuery(this).html());
        }
        else {
            alert("Select where you want to insert this variable first.");
        }
    });
});

请注意,当您单击文本区域(不先输入)然后单击变量时,它会正确填充。但是,它不适用于输入字段,也不适用于您开始手动输入文本区域然后单击变量。

这里发生了什么?为什么它只在这种情况下工作?我确定我遗漏了一些简单的东西,但我对 jQuery 还是很陌生,并且错过了一些更好的点。

【问题讨论】:

  • 为什么不使用 append 而不是 html?
  • @AnkurAggarwal append 将在文本区域中创建更多文本节点并产生意想不到的结果。要更改文本字段和文本区域的值,我们应该使用val()

标签: javascript jquery html


【解决方案1】:

试试这个,Fiddle Demo

prevFocus 是文本输入,val() 是您需要的,而不是 html()

if(typeof prevFocus !== "undefined") {
    prevFocus.val(prevFocus.val()+jQuery(this).html());
}
  • .val()方法主要用于获取input、select、textarea等表单元素的值
  • .html() 用于获取任意元素的内容

【讨论】:

    【解决方案2】:

    请试试这个FIDDLE 您的 jquery 代码略有变化

    jQuery(document).ready(function() {
            var prevFocus;
    
            jQuery("input[type=text], textarea").focus(function() {
                prevFocus = jQuery(this);
            });
    
    
    
            jQuery(".variable").click(function() {
                if(typeof prevFocus !== "undefined") {
                    prevFocus.val(prevFocus.html()+jQuery(this).html());
                }
                else {
                    alert("Select where you want to insert this variable first.");
                }
            });
    });
    

    【讨论】:

      猜你喜欢
      • 2013-01-13
      • 2016-03-13
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 2022-01-11
      相关资源
      最近更新 更多