I found some answers for this question, but non of them worked for me.
What I wants is to call function myFunc()
without refreshing page where href
wants.
This href
is doing his job with GET
request and I want it to stay in cause if someone have script block. It have to work without scripts too.
But when somebody hadn't dissabled script, then I wants to not go where href
redirect but do myFunc()
onclick
I had Tried something like this:
at javascript:
function onClickFunc(somedata){
event.preventDefault();
myFunc(somedata);
}
at html:
<a onclick="javascript:onClickFunc({{ some_django_data.id }})" href="?current={{ some_django_data.id }}{% if other_django_data %}&page={{ other_django_data.number }}{% endif %}">
When I replace href
body with #
and put javascript:myFunc({{ some_django_data.id }})
inside onclick
then it works.
Bit it's not soloution because people with script block would lose possibility of using my site.
What is wrong with this solution?
Two things:
onXyz
attribute-style handlers contain JavaScript code , so there's no need for the javascript:
pseudo-protocol.
Because you're coding a function call, if you want access to the event object, you need to pass it into the function
So:
onclick="onClickFunc(event, {{ some_django_data.id }})"
Then
function onClickFunc(event, somedata) {
event.preventDefault(); // Stops the default behavior of following the link
// ...
}
If you need to support really old browsers (or browsers hobbling themselves and behaving like really old browsers [I'm looking at you, IE9-IE11]), you'll need to allow for the possibility that preventDefault
isn't present on the event object. The good news is, though, that return false
in an onXyz
attribute handler prevents the default action. So:
So (note the return
) :
onclick="return onClickFunc(event, {{ some_django_data.id }})"
and (note the return
here too) :
function onClickFunc(event, somedata) {
if (event.preventDefault) {
event.preventDefault(); // Stops the default behavior of following the link
}
// ...
return false;
}
Your code is on the right track, but you forgot to pass the event object to the javascript function.
SEE THIS WORKING EXAMPLE:
function myfunc(event, data) { event.preventDefault(); alert("HELLO"); return false; }
<a onclick="myfunc(event, 'foo')" href="www.google.com">TESTER</a>
Note: You do not really need to specify the JS protocol. Have a look at this SO post .
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.