jQuery追加按钮后添加

时间:2016-04-15 03:24:53

标签: javascript jquery

以下是我的HTML:

<div class="row attachments-container">
    <div class="row">
        <div class="col-4 row-space-2 h5 invisible" id="js-first-photo-text">
            Your first photo appears in search results!
        </div>
    </div>
    <% if !@product.new_record? %>
        <% @product.product_attachments.each do |attachment| %>
            <div class="col-xs-6 col-md-4 form-group grayscale">
                <img src="<%= attachment.attachment.small.url %>" class="upload-photo-image">
                <input type="hidden" name="product_attachment[id][]" value="<%= attachment.id %>">
                <button class="delete-photo-btn overlay-btn js-delete-photo-btn delete-attachment" data-photo-id="143275119">
                    <i class="fa fa-trash-o"></i>
                </button>
                <button class="cover-photo-btn cover-overlay-btn js-delete-photo-btn cover-attachment" data-photo-id="143275119">
                    <i class="fa fa-picture-o"></i>
                </button>

            </div>
        <% end %>
    <% end %>

    <div class="col-xs-6 col-md-4 form-group">
        <div class="thumbnail panel photo-item empty-photo-frame" name="empty-photo-frame">
            <img src="<%= asset_url('add-image-placeholder.png') %>">
        </div>
    </div>

</div>

当用户决定更改cover之后onClick将触发:

$('.attachments-container').on('click', '.cover-attachment', function (event) {
    $this = $(this);
    var append_html = '<p class="status-notice">Saving as cover....</p>';
    $this.find('.cover-attachment').append_html

    var attachment_id = $(this).parent().find('input[name="product_attachment[id][]"]').val();
    $.ajax({
        type: "POST",
        url: "/product_attachments/" + attachment_id + "/set_cover",
        dataType: "json",
        data: {
            'attachment_id': attachment_id
        },
        complete: function (data) {
            $this.parent().find('.status-notice').text('Saved!').fadeOut('slow');
            console.log(data)
        }
    });
    event.preventDefault();
})

问题是,status-notice按钮后面没有附加cover-attachment

1 个答案:

答案 0 :(得分:4)

<强>问题:

问题出在以下声明中

$this.find('.cover-attachment').append_html

这将返回undefined,因为jQuery上没有方法/属性名append_html

<强>解决方案:

  

按钮

后面的Jquery 追加

要附加HTML,您可以使用append()

$this.find('.cover-attachment').append(append_html);

要完全替换/覆盖使用html()元素的HTML。

$this.find('.cover-attachment').html(append_html);
  

Jquery在按钮

之后追加

要添加新元素,请使用after()

$this.find('.cover-attachment').after(append_html);