简体   繁体   中英

Event function triggering when passing div ID

I'm trying to write some Javascript that when a div is clicked, a function is called with the parameter of that divs ID, the function works when I just send the hardcoded div id like so:

$('#areaOne').on('show.bs.collapse', onSectionClick('#areaOne'));


function onSectionClick(){
    var x = $('#areaOne).hasClass('toggled') ? 'false' : 'true';
    console.log(x)
}

However when I try it like this:

  $('#areaOne').on('show.bs.collapse', onSectionClick('#areaOne'));


  function onSectionClick(secID){
    var x = $(secID).hasClass('toggled') ? 'false' : 'true';
    console.log(x)
  }

Then the function is called as soon as the page is loaded, rather then when the area is clicked. I want it to work this way as there are many areas that should trigger the same function.

I'm pretty new to Javascript so any help, or advice on how to do this in a better way would be greatly appreciated.

The problem is that you call the function instead of giving a function reference. Try:

 $('#areaOne').on('show.bs.collapse', function(){onSectionClick('#areaOne')});

THe line

$('#areaOne').on('show.bs.collapse', onSectionClick('#areaOne'));

calls onSectionClick , passing in '#areaOne' , and passes its return avlue into on , exactly the way foo(bar()) calls bar and passes its return value into foo .

If you want to set it up to be called by the event, you pass a function reference rather than calling the function, eg:

$('#areaOne').on('show.bs.collapse', function() { onSectionClick('#areaOne'); });

In your case, though, you probably don't even want to do that. Instead:

$('#areaOne').on('show.bs.collapse', onSectionClick);
// Note no () -------------------------------------^

...and in onSectionClick , use this.id to get the ID of the clicked element ( 'areaOne' — add the # if you need it).

And if you have other "areas" that you also want to hook up, you can hook them up all at once:

$('selector-for-all-the-areas').on('show.bs.collapse', onSectionClick);

...and then you know which one relates to the event by which element this refers to in onSectionClick .

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