简体   繁体   中英

Remove All onclick Events for an Element

var links = document.body.querySelectorAll("p.sourcelinks a.individual_source_link");
for(var i=0;i<links.length;i++)
{
    links[i].onclick = null;
}

Is my current code, however it doesn't remove the onclick events. I have no idea what they will be since this is a greasemonkey script.

Your code only deals with events added by element.onclick case. What about events added with addEventListener (for standards compliant browsers) and attachEvent (for IE)?

You need to use removeEventListener and detachEvent to remove events as well as setting .onclick to null. Then all your bases will be covered.

This article would probably be useful:

http://www.computerhowtoguy.com/how-to-use-the-jquery-unbind-method-on-all-child-elements/

One part in particular is a recursive function that removes all click events. Remember that jQuery will remove click events IF the click event was created using jQuery. the function given in the article will remove both those created with jQuery and those that were not. The function given is this:

function RecursiveUnbind($jElement) {
    // remove this element's and all of its children's click events
    $jElement.unbind();
    $jElement.removeAttr('onclick');
    $jElement.children().each(function () {
        RecursiveUnbind($(this));
    });
}

You would call the function like this:

RecursiveUnbind($('#container'));

That function takes a jQuery object parameter, but you could easily change it up to pass a string as the name of the ID for the element, or however you think is best.

While this only addresses click events you could easily modify it to handle others or all.

That code doesn't work because of GM's sandbox. links is in an XPCNativeWrapper .

To get around this use setAttribute() , like so:

var links = document.body.querySelectorAll("p.sourcelinks a.individual_source_link");
for(var i=0;i<links.length;i++)
{
    links[i].setAttribute ("onclick", null);
}


Note that click handlers that are set other ways, will need to be cleared other ways ( removeEventListener() , for example).

I am guessing you have either an href or a JavaScript function being called on the onClick for an <a> link.

You can remove either of these by removing the href tag, the onClick event or in this case both of them.

    for(var i=0;i<links.length;i++)
    {

        links[i].href='#';
        links[i].onclick = '';
    }

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