简体   繁体   中英

Alter an existing onClick function with Javascript

My query is regarding using Javascript to change the value of an onclick function that already exists on the page.

There's a button. This button has the following onclick function:

onclick="if (confirm('Yahdy Yahdy yah?')) { someFunction(); }; return false;"

I would like to change the onclick function using Javascript to just be as follows and or extract the someFunction(); and run that directly without having to go through the confirmation. As I understand it, you can't confirm a confirm through scripting, so my only option is to run someFunction(); directly. My question is, how do I access someFunction() directly as someFunction() contains randomly generated values each time the page loads.

onclick="someFunction();"

That's basically what I'd like, so I can then call onclick() directly. I'm happy to use vanilla or jQuery to go about this.

TLDR: I want to extract PART of the old onclick function and make a new onclick function with JUST that part.

You can do this:

var code = obj.onclick.toString();

That will give you the javascript code assigned to that click handler to which you can search through it, find what you're looking for and reassign the click handler to something else.


I have no idea if this is the best way to do it, but here's something that worked for me:

function nullConfirm() { return true;};

(function() {
    var obj = document.getElementById("test");
    var code = obj.onclick.toString();
    code = code.replace("confirm(", "nullConfirm(");
    var matches = code.match(/\{(.*)\}/);
    if (matches) {
        obj.onclick = function() {
            eval(matches[1]);
        }
    }
})();

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