简体   繁体   中英

removing the div appended using append method

this is my code...append is working but removing is not working. how to remove the appended div?

<html>
  <head>
    <script type="text/javascript">
      function view(){
        $('body').append('<div class="added"><p>something</p></div>');
      };
      function close(){
        $('.added').remove();
      } ;
    </script>
  </head>
  <body>
    <a onclick="view();">something</a>
    <a onclick="close();">close</a>
  </body>
</html>

Specify window.close in your html handler:

   <a onclick="window.close();">close<a>

http://jsfiddle.net/ZTwd7/1/

Otherwise close() refers to the native close method, which doesn't do anything.

Here's how you would emulate it with a "javascript" (as opposed to inline html attribute) handler:

elem.onclick = function(event) {
    with(Window.prototype) {
        with(document) {
            with(this) {
                close();
            }
        }
    }
};

This is not exact reproduction (nor does it work in IE etc, that's not the point) but it would put the .close in Window.prototype in front of the global window.close in the scope, so it shadows it. You can still refer to it explicitly with window.close() .


You should also totally drop the above and use jQuery instead:

<a id="view">something<a>
<a id="close">close<a>

JS:

$(function() {
    $("#view").click(function() {
        $('body').append('<div class="added"><p>something</p></div>');

    });
    $("#close").click(function() {
        $('.added').remove();

    });
});​

http://jsfiddle.net/ZTwd7/5/


Making an ajax request that fetches a html file to be appended:

$.get("myhtml.html", function(html) {
    $("body").append(html);
}, "html");

Don't know why but by putting another name to close function instead of close() it works

<html>
    <head>
<script src="http://code.jquery.com/jquery-latest.js"></script>

   <script type="text/javascript">
            function view(){
                     $('body').append('<div class="added"><p>something</p></div>');
            };
            function close_it(){
                                       $('.added').remove();

            } ;

    </script>
</head>
<body>
   <a onclick="view();">something<a>
   <a onclick="close_it();">close<a>
</body></html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM