输入未正确填充

时间:2016-03-09 20:42:36

标签: javascript jquery

第一个输入我可以在点击图像时填写URL。

当我添加新输入并单击图像时,URL显示在按钮ADD上,而不是在具有焦点的输入中

https://jsfiddle.net/gislef/wyp4hzrd/

var input = '<label>Nome: <input type="text" name="images[]" /> <a href="#" class="remove">X</a></label></br>';

    $("input[name='add']").click(function( e ){
        $('#inputs_add').append( input );
    });

    $('#inputs_add').delegate('a','click',function( e ){
        e.preventDefault();
        $( this ).parent('label').remove();
    });


var focused = null;

$("input").on("focus", function() {
  focused = $(this);
})

$("img").click(function() {
  if (focused.length)
  focused.val($(this).attr("src"));
})

使用固定输入我可以正常工作:

Fill inputs with urls images

2 个答案:

答案 0 :(得分:1)

请与代表一起尝试,如下所示:

var input = '<label>Nome: <input type="text" name="images[]" /> <a href="#" class="remove">X</a></label></br>';

    $("input[name='add']").click(function( e ){
        $('#inputs_add').append( input );
    });

    $('#inputs_add').delegate('a','click',function( e ){
        e.preventDefault();
        $( this ).parent('label').remove();
    });


var focused = null;

$(document).delegate("input", "focus", function() {
  focused = this;
  console.log(focused);
});

$("img").click(function() {
  if ($(focused).length)
  $(focused).val($(this).attr("src"));
});

答案 1 :(得分:1)

由于您正在创建动态控件

,因此无法正确添加链接
$("input").on("focus", function() {
  focused = $(this);
})

以上代码正在运行并正确绑定到fieldset中的第一个输入

您需要使用包含子输入的父字段集上的委托替换此代码,以便注册动态控件。

$("fieldset").delegate("input", "focusin", function() {
  focused = $(this);
})

这是一个工作小提琴,我认为是预期的行为

https://jsfiddle.net/wyp4hzrd/1/