是否可以使用JavaScript同时触发2个事件?

时间:2018-04-25 21:32:15

标签: javascript jquery html css css3

我试图通过点击"过去的位置"同时触发2个事件。在右侧导航链接跳转到底部页面到过去的位置"同时划分和路由默认图像映射(印第安纳波利斯地图)。

目前,它跳到页面底部就好了,但图像地图消失了 - 只是没有显示在地图的占位符中。

HTML - 另外两个工作链接路由图像映射

<li class="j_linkHover">
  <a href="#mapCO-asp" class="j_linkThumb">Aspen, CO</a>
  <p class="j_accordion-panel"><span class="j_dateLocation">Central Regions<br>May 29 - June 3</span></p>
</li>

<li class="j_linkHover">
  <a href="#mapOR" class="j_linkThumb">Salem, OR</a>
  <p class="j_accordion-panel"><span class="j_dateLocation">Oregon School for the Deaf,<br>Washington School for the Deaf, <br> Non-Profit Community Event<br>June 3 - 6</span></p>
</li>

<li  class="j_linkHover">
  <a href="javascript: document.body.scrollIntoView(false);" id="location-color" class="j_linkThumb  is-active">Past Locations</a> <--- jumps to the bottom, but cannot route image map at the same time
</li>

JavaScript - 这会在占位符

中路由图像映射
$(document).ready(function(){

  //Default Action
  $(".mapActive").css({'display':'none'});
  $("ul.j_linkLocation li#mapIN").addClass("active").show(); //Activate first tab
  $(".mapActive#mapIN").show(); //Show first tab content

  //On Click Event
  $("ul.j_linkLocation li").click(function() {
    $("ul.j_linkLocation li").removeClass("active"); //Remove any "active" class
    $(this).addClass("active"); //Add "active" class to selected tab
    $(".mapActive").css({'display':'none'}); //Hide all tab content
    var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
    $(activeTab).fadeIn('fast'); //Fade in the active content
    return false;
  });

});

enter image description here enter image description here

2 个答案:

答案 0 :(得分:2)

要重用相同的功能,请在函数中定义它:

function routeImages (elem) {
  $("ul.j_linkLocation li").removeClass("active"); //Remove any "active" class
    $(elem).addClass("active"); //Add "active" class to selected tab
    $(".mapActive").css({'display':'none'}); //Hide all tab content
    var activeTab = $(elem).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
    $(activeTab).fadeIn('fast'); //Fade in the active content
} 

所以现在你的旧代码就像这样:

//On Click Event
  $("ul.j_linkLocation li").click(function() {
    routeImages($(this));
  });

然后为列表项添加一个单击侦听器:

$('#location-color').parent('li').on('click', function() {
  //the first event
  $('body').scrollIntoView(false);

  //call the function for routing images
  routeImages($('ul.j_linkLocation li:first'));
});

答案 1 :(得分:2)

是的...使用jQuery,这是一个JavaScript库...您可以将多个event附加到元素。

$([element selector]).on([events... space separated], [Delegated selector], function([arg]){
  //  Whatever to execute
});

更具体的例子(对语法有用):

$("#myDiv").on("click mouseenter mouseleave tap touchstart touchend", ".innerBox", function(event){
  //  Whatever to execute
});

了解jQuery event handler

这是我所知道的最完整的event list

额外阅读将是event delegation ...