Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

javascript - preventDefault won't work on Firefox

I'm trying to prevent A HREF from actually opening the link, but to execute a script. I got the script part working, but it seems Firefox would just ignore this:

$("#permalink a").click(function(id){
  $("#newPost").fadeToggle;
  event.preventDefault();
  var id = this.getAttribute('href');
  $("#newPostContent").load(id);
  $("#newPost").show("fast");
});

Can anyone suggest a cross-browser script for preventing defaults?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The standard solution to this is to return false from the click() handler. return false is the equivalent of calling preventDefault() and stopPropagation() on the event. preventDefault() is sufficient for this task too so either it or return false will work.

Your problem seems to be syntax errors and misnamed parameters. I see:

  • fadeToggle has no parentheses;
  • the function parameter is called id yet you call event.preventDefault(); and
  • You're fading the post and then immediately showing it? That'll queue two animations but doesn't make a lot of sense. You probably want to chain together those two things and the load() in a rational manner.

So this should work:

$("#permalink a").click(function(event) {
  $("#newPost").fadeToggle();
  var id = this.getAttribute('href');
  $("#newPostContent").load(id);
  $("#newPost").show("fast");
  return false;
});

You can freely replace return false with event.preventDefault() in this instance but the propagating click() event might or might cause other issues depending on what other event handlers you have.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...