Cancel onClick javascript functions with another javascript

Hi

This is a bit sticky situation, and I need some advice.

I have a couple href like this in my project.

<a class="not-allowed" href="javascript:void(0)" onclick="showSettingDiv();">Change</a>
<a class="" href="javascript:void(0)" onclick="DeleteSettingDiv();">Delete</a>

Depending on the type of login, I have to have some links, do nothing, and run something else.

I have this function to make this happen:

$('.not-allowed').each(function (e) {
    $(this).click(function (e) {
        e.preventDefault();
        alert("you dont have permission");
     })
 });

This activates a warning, however it also performs my onclick function. is there a way i can stop all javascript functions and execute only this above one?

I realized that I could just use it .removeAttr(), but I'm not sure if this is the best way. I mean, I can have buttons for a restriction or a checkbox and a switch for disabling.

e.preventDefaultwill not take care of everything that I suppose. In any case, how to prevent all javascript functions?

Thank.

+3
4

. . DOM- . , JS .

EventListener , stopProgagation Event.

:

<html>
<body>
    <button class="not-allowed" id="btn1" onclick="alert('onclick executed');">BTN1</button>
    <button id="btn2" onclick="alert('onclick executed');">BTN2</button>

<script type="text/javascript">
    document.addEventListener("click", function (event) {
        if (event.target.className.indexOf("not-allowed") > -1) {
            event.stopPropagation();    // prevent normal event handler form running
            event.preventDefault();    // prevent browser action (for links)
        }
    }, true);
</script>

</body>
<html>
+2

.preventDefault() inline. . :

$('.not-allowed').each(function(i, elem) {
    elem.onclick = null; 
    $(this).click(function (e) {
        e.preventDefault();
        alert("you dont have permission");
     })
});

jsfiddle: http://jsfiddle.net/cJcCJ/

+2

click , "" , e.stopPropagation();, .

if($(this).hasClass('disabled')) return; .

0
source

You will need to change the functions in onclick( showSettingDiv, DeleteSettingDiv) to check permissions.

BTW, make sure that you not only check permissions in JavaScript, but also have to do this on the server side, or it is very easy to manipulate.

0
source

Source: https://habr.com/ru/post/1796307/


All Articles