简体   繁体   中英

<button> always redirecting after clicked

My button:

<button onclick="return DeleteImg(this,event);">Delete</button>

My code:

function DeleteImg(Obj,e) {
    if (!confirm('Are you sure you want to delete the file?')) return false;
    var n = new PostData('/Pictures/Delete/', 'Type=Home&Name=' + window.LargeImage.src.split('/')[5]);
    n.onResponse = function (t) {
        var n = JSON.parse(t);
        if (n.Success) ShowMsg('Image Deleted, it will be gone when you refresh.');
        else ShowMsg(n.Msg);
    };
    e.preventDefault();
    return false;
}

Post data function:

function PostData(e, t) {
    var n = false;
    this.onResponse = function (e) {};
    if (window.XMLHttpRequest) n = new XMLHttpRequest;
    else if (window.ActiveXObject) n = new ActiveXObject('Microsoft.XMLHTTP');
    else {
        this.onResponse(JSON.stringify({
            Success: false,
            Msg: 'Your browser does not support AJAX, please upgrade to Google Chrome, Mozzila Firefox or Internet Explorer 10',
            ElementId: undefined
        }))
    }
    n.open('POST', e, true);
    n.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var r = this;
    n.onreadystatechange = function () {
        if (n.readyState == 4 && n.status == 200) r.onResponse(n.responseText)
    };
    n.send(t)
}

Whenever the button is clicked and the user clicks okay to the confirmation box, the page redirects to another page (No idea what, my FCP just redirects it to page not found though so it doesn't exist) and the code isn't ran.

What can I do to fix this?

By default a button is a submit button which causes your page to redirect. You can fix by setting the button type.

<button type="button" onclick="return DeleteImg(this,event);">Delete</button>

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