开发者

problem with adding input in jQuery

开发者 https://www.devze.com 2023-03-22 12:05 出处:网络
why after two click this code adding several input together? $(\'.add_input\').live(\'click\', function () {

why after two click this code adding several input together?

$('.add_input').live('click', function () {
            var scntDiv = '.'+$(this).closest('div.find_input').find('div').attr('class');
            var i = $('.adding').size();
            var input = $(scntDiv).clone().wrap("<div>").parent().html();
            alert(scntDiv)
            $(scntDiv + ' .add_input').remove();            
            $(input).appendTo(scntDiv);
            $('<div><a href="" class="remove_input"></a></div>').appendTo('.add_in');
            $(scntDiv + ' .add_in div a:first').remove('')
            i++;
            return false;
        });

html: (i use of this html twice)

<div class="column find_input">
    <div class="ai_service">
            <div class="column">
                <div class="mediumCell">
                    <input type="text" name="name" style="width: 160px;" placeholder="خدمات دیگر" title="نام پکیج تور خارجی">
                </div>
            </div>
            <div class="column" style="margin: 5px 3px;">
                <div clas开发者_JAVA百科s="mediumCell add_in">
                    <a href="" class="add_input"></a>
                </div>
            </div>
    </div>
</div>


Hmm if you're just trying to add an extra input field, your code seems a little overcomplicated for that... Try this?

$('a.add_input').live('click', function(e) {
    e.preventDefault();
    var $this = $(this);
    var $wrapper = $this.closest('div.find_input');
    var $input = $wrapper.find('input[name=name]').eq(0).clone();
    $wrapper.children('div').eq(0).append($input);
};

I didn't replicate everything from your code, just the cloning/adding new input. If you posted simplified code and my example doesn't apply, I apologize. Also, I think you wanted to append your cloned input into div.ai_service?

In terms of why your original code adds multiple inputs, the cloning process you go through probably first clones one input, adds it, clones the whole thing again (2 inputs), adds 2, and so on. You can use $().eq(0) to limit your jQuery object to the first element it finds that matches your selector.


Try this

 $('a.add_input').live('click', function (e) {
    e.preventDefault();
    var $column = $(this).closest("div.column");
    var input = $column.prev("div.column").clone().wrap("<div />").parent().html();
    $column.before($(input));

});
0

精彩评论

暂无评论...
验证码 换一张
取 消