简体   繁体   中英

A javascript/jquery function to delete itself after execution

I am sending an ajax request to one of my controller to update the user interaction (which page he visits/likes) for an very insight analytics. I am storing these information in my mongo db.

All I want is, on success of this request, delete this script. But all the alert works, but the script never deletes. The following is my code

<div id="delete_this">
<script>
$(document).ready(function() {
  $.ajax({
    url: weblink+'user-interactions',
    type: 'POST',
    dataType: 'html',
    data: {
        //some post data
    },
   })
   .done(function(html) {
        alert("works");
        var status = "executed";
        alert("works here");
            $("#delete_this").remove();

    })
    .fail(function(html) {
        console.log("error");
    });


});
</script>
</div>

WHAT I HAVE DONE TILL NOW:

1) tried with adding a div as the parent and pointing to delete that div as shown in script.

2) separated out the .remove() from the script into a new script tag and used something like this.

<script>
$(document).ready(function() {
    $("#delete_this").remove();
});
</script>
  1. tried to specify the parentnode and delete the child.

I failed in all three attempts. I am really stuck out here.

Any reasons why it is not working?

I also have another question relating to this.

This link says that the javascript stays in the session till the page is refreshed. So why are'nt we following a standard where we can execute the scripts and delete them By doing so, we will be able to achieve building a bit more secured webpages. Is'nt it?

You could use plain Javascript to do this (not tested this)

var domNode = document.getElementById('delete_this');
var nodeParent = domNode.parentNode;
nodeParent.removeChild(domNode);

Not sure this is ideal but it should remove it completely from the DOM.

This works :

<button>remove</button>

<script id="test">
$( "button" ).click(function() {
  $( "#test" ).remove();
  alert("removed " + ($( "#test" ).length == 0));
});
</script>

try it here: http://jsfiddle.net/4ungb/

So either you have a) other errors that prevent that script to complete or b) your criteria for testing deletion is not correct.

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