簡體   English   中英

Onclick刪除附加的Div - JQuery

[英]Onclick remove appended Div - JQuery

如何在單擊特定Div的“X”按鈕時刪除附加行。

這是JsFiddle DEMO: http //jsfiddle.net/7jE9p/4/

我也在這里提供CODE:

HTML:

      <p>
          <a href="javascript:void(0);" class="add_more">Add More</a>
      </p>

<table border="0" width="500" cellspacing="0">
   <tbody class="append_data"></tbody>

<tr>
  <td> 
      <textarea name="description" id="description"></textarea>
  </td> 
</tr> 

</table>    

CSS:

#description{
    width:400px;    
}

.description_text{
    border:#333333 solid 1px;
    width:400px !important;
}

.append_data{
   white-space: pre-wrap;      /* CSS3 */   
   white-space: -moz-pre-wrap; /* Firefox */    
   white-space: -pre-wrap;     /* Opera <7 */   
   white-space: -o-pre-wrap;   /* Opera 7 */    
   word-wrap: break-word;      /* IE */
}

JQuery的:

$('.add_more').click(function()
                     {
                        var description = $('#description').val();
                         $(".append_data").append('<div class="description_text">'+description+' <a href="javascript:void(0);">X</a></div><br><br>');

                     });

試試這個,對於動態添加的元素,你需要在最近的靜態元素上使用on()和delgate,如下所示:

$('.append_data').on('click','.description_text a',function(){
     $(this).closest('.description_text').remove();
});

DEMO

您可以添加到description_text css

margin-bottom:10px;

並忽略添加<br/>到附加

DEMO

正如@anton所說。 或者你可以根據這個小提琴將remove事件添加到元素本身(但Anton的解決方案更好)

$('.add_more').click(function(){
    var description = $('#description').val();
    $newEl = $('<div class="description_text">'+description+' <a href="javascript:void(0);">X</a></div>');
    $newEl.on("click", function(){$(this).remove();});
    $(".append_data").append($newEl);
});

或者將X作為關閉觸發器,如下所示:jsfiddle.net/7jE9p/9

    $newEl.on("click", "a", function(){$(this).parent().remove();});

我在這看到很好的答案。 無論如何,最好的選擇是在函數范圍內的變量中存儲元素。 然后,您可以輕松刪除與特定單元格連接的每個元素。

http://jsfiddle.net/7jE9p/8/

JS:

$('.add_more').click(function () {
    var description = $('#description').val();
    var deleteButton = $('<a href="javascript:void(0);">X</a>');
    var cell = $('<div class="description_text">' + description + '</div>');
    var spaces = $('<br /><br />');

    cell.append(deleteButton);

    $(".append_data").append(cell);
    spaces.insertAfter(cell);

    deleteButton.click(function () {
        cell.remove();
        spaces.remove();
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM