cancel onClick javascript functions with another javascript
HI there,
this is a little sticky situation and I need some advice.
I have a couple of href's like this, across 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 user logged in, I have to have some links do nothing and trigger something else.
I have this function to make that happen:
$('.not-allowed').each(function (e) {
$(this).click(function (e) {
e.preventDefault();
alert("you dont have permission");
})
});
This does fire up the alert, however, it also executes my onclick function too. is there a way I Can stop all javascript functions and execute just this above one?
I realized I could just use .removeAttr()
but I am not sure if thats the best way. I mean I might have buttons to restrict or checkbox and radio button to disable.
e.preventDefa开发者_Go百科ult
will not take care of all that I guess. Anyway, How do I prevent all javascript functions ?
Thanks.
Yes. It is called Capture mode. It works on DOM-compatible browsers. Check out if your JS framework makes this function available for you.
If the capturing EventListener wishes to prevent further processing of the event from occurring it may call the stopProgagation method of the Event interface.
A quick example:
<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>
.preventDefault()
does not have an affect on inline event handlers. You would need to remove the functionality completely. Give this a shot:
$('.not-allowed').each(function(i, elem) {
elem.onclick = null;
$(this).click(function (e) {
e.preventDefault();
alert("you dont have permission");
})
});
Simplified example on jsfiddle: http://jsfiddle.net/cJcCJ/
You could bind the click
event on a parent element and then bind another click event on the "inactive" elements which will call e.stopPropagation();
to prevent the event from bubbling up to the parent element.
Another solution would be giving the disabled elements a class and doing if($(this).hasClass('disabled')) return;
in the handler.
You will need to have to modify the function(s) in onclick
(showSettingDiv
, DeleteSettingDiv
) to check for the permissions, too.
BTW, make sure that you don't only check permissions in JavaScript, you must also do it server-side, or it's very easy to manipulate.
精彩评论