簡體   English   中英

動態創建和刪除HTML元素

[英]Create and remove HTML-Element dynamically

如何動態創建HTML元素,對其進行處理,然后將其刪除。 但是重要的是將其真正刪除。 這是我的方法:

var newdiv = document.createElement('div');
newdiv.setAttribute('id','MyDiv');
$('#MyDiv').css({'width':'100px','height':'100px'});
$('#MyDiv').html('This is a test');

$('#MyDiv').remove(); // It should be work ?

// Is it possible to delete it as follows?
newdiv.remove();

正如我提到的,真正刪除元素很重要,因為函數“ createElement()”通常可以被調用。

如何測試新創建的HTML元素是否已真正刪除?

我測試如下,該元素是否仍然存在,但是我總是正確的!

alert(  $('#MyDiv').length == 1);

以下是兩個鏈接,但它們不足以解決我的問題。

動態設置輸入元素的id屬性

createElement並刪除DOMElement

謝謝。

試試這個也許是你想要的:

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
     var div =  document.createElement("div");
     $(function(){
        $("body").append( div);
        $(div).css({'width':'100px','height':'100px','border':'solid 1px black'}).html('This is a test');
        //$(div).remove();
     });
    </script>
  </head>
  <body>
  </body>
</html>

不要忘了// $(div).remove();

首先,我知道,您在此行的代碼中有一個錯誤:

newdiv.setAttribute('id','#MyDiv')

id屬性的值不能為'#'(井號)-您的代碼元素newdiv的ID如“ #MyDiv”,但這對jQuery無效,因為jQuery使用此模板作為ID選擇器(“# idName”)

您可以用自己的方式動態刪除元素,但是我想以前應該使用jQuery.append(you element / selector)方法將其附加到頁面上的另一個元素上。

如果可以使用jQuery,則可以嘗試以下操作:

$( "body" ).append( "<div id="MyDiv">This is a test</div>" ); // Create MyDiv div before </body> tag (you can use .prepend( ... ) to create it after <body>)

$("#MyDiv").css({'width':'100px','height':'100px'}); // Give some style to MyDiv

$("#MyDiv").remove(); // Delete MyDiv

暫無
暫無

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

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