简体   繁体   中英

e.preventDefault(); Not Working in Firefox

I have a linked image using Handlebars.js with the following markup:

<a href="#" class="clicker" onclick="toggle_visibility('details-{{@index}}');change_icon('img-{{@index}}');">
  <img class="reveal" id="img-{{@index}}" src="img/list-icon.svg" alt="reveal" />
</a>

with corresponding JavaScript using Jquery:

function toggle_visibility(id) {
  var e = document.getElementById(id);
  if ( $(e).is( ":hidden" ) ) {
    $(e).slideDown( "fast" );
  } else {
    $(e).slideUp( "fast" );
  }
  e.preventDefault();
}

function change_icon(id)  {
  var e = document.getElementById(id);
  var src = $(e).attr('src');
  if ( src == "img/list-icon.svg" ) {
    $(e).attr('src',"img/x-icon.svg");
  } else {
    $(e).attr('src',"img/list-icon.svg");
  }
  e.preventDefault();
}

This works perfectly in Chrome and Safari but in Firefox, although the two functions do what they are supposed to do, the screen jumps to the top of the page on click and I get the following error:

TypeError: e.preventDefault is not a function

I've also tried return false; which displays no error but still brings the page to the top. And I don't know how to avoid using the inline Javascript in my HTML since I'm using Handlebars.

How can I solve this bug?

You are using the element as the event object. You can pass the event as an argument if you want to use inline event handlers:

<a href="#" class="clicker" onclick="toggle_visibility(event, 'details-{{@index}}');change_icon(event, 'img-{{@index}}');">
  <img class="reveal" id="img-{{@index}}" src="img/list-icon.svg" alt="reveal" />
</a>

function toggle_visibility(e, id) {
  e = e || window.event; // Cross browser support
  var elem = document.getElementById(id);
  if ( $(elem).is( ":hidden" ) ) {
    $(elem).slideDown( "fast" );
  } else {
    $(elem).slideUp( "fast" );
  }
  e.preventDefault();
}

function change_icon(e, id)  {
  e = e || window.event; // Cross browser support
  var elem = document.getElementById(id);
  var src = $(elem).attr('src');
  if ( src == "img/list-icon.svg" ) {
    $(elem).attr('src',"img/x-icon.svg");
  } else {
    $(elem).attr('src',"img/list-icon.svg");
  }
  e.preventDefault();
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM