简体   繁体   中英

e.preventDefault() and e.stopPropagation() not working as expected

The app in question is basically a DOM inspector tool similar to the one available in Chrome Dev Tools made using plain JS. Basically when the user clicks on an element attributes such as class names, xpaths and texts should be available to the user. I have run into a problem which is: When a user clicks on an element such as a link or a button, the browser navigates to the intended page. I have tried to prevent this problem using the following piece of code:

var target = getSelectedElementFromPoint(e.clientX, e.clientY); // target has the element the user wants to inspect
if(target.nodeName.toLowerCase() == "a" || target.nodeName.toLowerCase() == "button"){
        e.stopPropagation(); // e is the event
        e.preventDefault();
 }

The intention of the code is to get the element the user clicks on, check if it is an anchor tag or a button and if so, stop the event from progressing further. However, it does not work as expected as, on mouse click, it still navigates to the page.

Any help would be appreciated.

EDIT: Please note that I cannot use jQuery in this particular instance. Thanks

EDIT2: Probably should have mentioned this earlier but I forgot. I have actually tried return false as well. Using return false achieves the required functionality but the only problem being, once the user leaves the "Inspect mode" that link is no longer clickable and that is not desirable behavior.

Basically what I want is that when the user enters the "Inspect mode" for all links to be unclickable. And these links should be clickable once "Inspect mode" is removed. Rather than disable all links on the page, I thought of disabling the one the user clicked on.

The solution is to simply wrap your code in a check for 'inspectMode' . 'inspectMode' should be a boolean var.

Add the foloowing code to your eventhandler:

if (inspectMode)
{
    var target = getSelectedElementFromPoint(e.clientX, e.clientY);
    if(target.nodeName.toLowerCase() == "a" || target.nodeName.toLowerCase() == "button")    
    {
        e.stopPropagation(); // e is the event
        e.preventDefault();
        return false;
    }
}
return true;

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