简体   繁体   English

e.preventDefault(); 在Firefox中无法使用

[英]e.preventDefault(); Not Working in Firefox

I have a linked image using Handlebars.js with the following markup: 我有一个使用Handlebars.js的链接图像,带有以下标记:

<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: 使用相应的JavaScript使用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: 这在Chrome和Safari中完美运行,但在Firefox中,尽管这两个功能可以完成应有的作用,但单击鼠标后屏幕会跳至页面顶部,并且出现以下错误:

TypeError: e.preventDefault is not a function

I've also tried return false; 我也尝试过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. 而且我不知道如何避免在HTML中使用内联Javascript,因为我使用的是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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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