Say I have a link:
<a href="">Example!</a>
I want to keep the link intact, but I'd like an onclick event to decide if the link is clickable or not
<a onclick='stopLight()' href="">Example!</a>
function stopLight() {
// conditional logic
// return true or return false
}
so if stopLight() == true, then link works, if stopLight() == false, then link doesn't. Is making this possible without changing the href, because I'd rather not
Say I have a link:
<a href="http://www.example.">Example!</a>
I want to keep the link intact, but I'd like an onclick event to decide if the link is clickable or not
<a onclick='stopLight()' href="http://www.example.">Example!</a>
function stopLight() {
// conditional logic
// return true or return false
}
so if stopLight() == true, then link works, if stopLight() == false, then link doesn't. Is making this possible without changing the href, because I'd rather not
Share Improve this question asked Dec 14, 2012 at 16:02 Shai UIShai UI 52k77 gold badges218 silver badges316 bronze badges 2-
2
onclick='return stopLight()'
is the correct syntax – mplungjan Commented Dec 14, 2012 at 16:06 - Are you using jQuery/some framework or raw JavaScript? – Jordan S. Jones Commented Dec 14, 2012 at 16:06
4 Answers
Reset to default 4Use return stopLight()
for the onclick
handler.
As mplungjan suggested in his ment
In order to cut the default action:
stopLight = function (e) {
window.event.preventDefault();
}
This will prevent the event from happening.
So you could do:
<a onclick='isStopLight()' href="http://www.example.">Example!</a>
And in the JS
isStopLight= function(){
if(stopLight()){
window.event.preventDefault();
}
}
stopLight = function () {
// conditional logic
// return true or return false
}
Cheers.
You could do this with jQuery, and the event.preventDefault() method:
$('a.yourLink').on('click',function(e){
if (stopLight()){
e.preventDefault();
}
});
if stopLight is true the default behavior of <a>
will be prevented, else it executes normal
Plain JS
- inline
<a onclick='return stopLight()' href="http://www.example.">Example!</a>
- unobtrusive:
window.onload=function() {
document.getElementById("stoplight").onclick=function() {
// conditional logic
// return true or return false
}
}
<a id="stoplight" href="http://www.example.">Example!</a>
jQuery
<a id="stoplight" href="http://www.example.">Example!</a>
$(function() {
$("#stoplight").on("click",function(e) {
// conditional logic
if (false condition) e.preventDefault(); // (or return false;)
});
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744084821a4555973.html
评论列表(0条)