2015-08-27 3 views
0

HTML:Как добавить элемент после последнего дочернего элемента?

<div class="uploader" id="uniform-file"> 
    <input type="file" name="data[Tolet][images][]" class="span12 tolet_img" id="file" style="width: 100%; opacity: 0;" size="20"><span class="filename">No file selected</span><span class="action">Choose File</span> 
</div> 

<div class="uploader" id="uniform-file"> 
    <input type="file" name="data[Tolet][images][]" class="span12 tolet_img" id="file" style="width: 100%; opacity: 0;" size="20"><span class="filename">No file selected</span><span class="action">Choose File</span> 
</div> 

JQuery:

$(document).ready(function(){ 
    $('.tolet_img').click(function(){  
     var htmlString = $('.uploader').clone(true); 
     $('.uploader').children().last().after(htmlString); 
    });  
}); 

Я ожидаю, что следующий вывод после одного клика.

<div class="uploader" id="uniform-file"> 
    <input type="file" name="data[Tolet][images][]" class="span12 tolet_img" id="file" style="width: 100%; opacity: 0;" size="20"><span class="filename">No file selected</span><span class="action">Choose File</span> 
</div> 

<div class="uploader" id="uniform-file"> 
    <input type="file" name="data[Tolet][images][]" class="span12 tolet_img" id="file" style="width: 100%; opacity: 0;" size="20"><span class="filename">No file selected</span><span class="action">Choose File</span> 
</div> 

    <div class="uploader" id="uniform-file"> 
     <input type="file" name="data[Tolet][images][]" class="span12 tolet_img" id="file" style="width: 100%; opacity: 0;" size="20"><span class="filename">No file selected</span><span class="action">Choose File</span> 
    </div> 

Но это не сработает. Что я делаю не так?

ответ

3

Попробуйте это: вы можете использовать :last, чтобы получить последний загрузчик и использовать .after, чтобы положить новую загрузившие

$(document).ready(function(){ 
    $('.tolet_img').click(function(){ 
    var htmlString = $('.uploader:last').clone(true); 
    $('.uploader:last').after(htmlString); 
    }); 
}); 

Примечания - Вы помещаете то же идентификатор для каждого клонированного пользователя, который не является хорошей практикой. Вместо этого вы можете изменить идентификатор с помощью какого-либо счетчика или переменной, как показано ниже.

$(document).ready(function(){ 
     var uploaderCount = 0; 
     $('.tolet_img').click(function(){ 
     var $htmlString = $('.uploader:last').clone(true); 
     $htmlString.attr('id', 'uniform-file-'+uploaderCount); 
     uploaderCount++; 
     $('.uploader:last').after($htmlString); 
     }); 
}); 
+0

это прекрасно работает. но когда я выбираю файл для второго или третьего поля ввода, он остается пустым. –

+0

попробуйте изменить идентификатор ввода файла как загрузчика. используйте '$ htmlString.find ('input [type = file]'). attr ('id', 'file -' + uploaderCount);' –

Смежные вопросы