So I'm trying to use .each to iterate through an unordered list where each element has a tag. If the element has "tag1", then the element is shown on screen, if not then the element is hidden.
The problem is when I used .each, for each iteration I want it to call a user-defined function typeCheck().
Case 1
index.html
- <a href="#" id="button">Button</a>
- <ul id="list">
- <li class="tag1">Item 1</li>
- <li class="tag1">Item 2</li>
- <li class="tag2">Item 3</li>
- <li class="tag3">Item 4</li>
- <li class="tag1">Item 5</li>
- </ul>
script.js
- $(document).ready(function(){
- function typeCheck(currElem, tag){
- if ($(currElem).hasClass(tag)) {
- if($(currElem).is(":hidden")) {
- $(currElem).fadeIn();
- }
- } else {
- $(currElem).fadeOut();
- }
- }
-
- $("#button").click(function(){
- $("#list li").each(typeCheck(this, "tag1"));
- });
- });
Demo of Case 1
Now when I try this, I get an error in the Chrome console: "Uncaught TypeError: Cannot call method 'call' of undefined". Also apparently a ninja bug has slipped into this because "Button" disappears when you click on it... weird.
Case 2
So checking to see if something was wrong with my logic, I replaced the code in typeCheck with a simple console.log() call.
- $(document).ready(function(){
- function typeCheck(){
- console.log("test");
- }
-
- $("#button").click(function(){
- $("#list li").each(typeCheck());
- });
- });
It prints out "test" once and then gets the same error. So it seems like it's calling the function once successfully though.
Case 3So instead of using a user-defined function, I just have jQuery call the function directly like this:
- $(document).ready(function(){
- $("#button").click(function(){
- $("#list li").each(function(){
- if ($(this).hasClass("tag1")) {
- if($(this).is(":hidden")) {
- $(this).fadeIn();
- }
- } else {
- $(this).fadeOut();
- }
- });
- });
- });
Demo of Case 3
Here the behavior works fine, and the function code is verbatim to the first two cases, so I think my general logic is right.
So why aren't the first two cases working as intended and what's up with the weird ninja bug in case 1? I know I can just use case 3 since it works, but I would like to keep my code more on the organized side. I'm calling this function quite a bit, and it's kind of annoying having to copy and paste a buncha code when a user-defined function would suffice...