This is how I tried to call the setState(id)
function for every option in my menu. It doesn't work. Maybe there is another way to do this properly?
I know that a function inside a function is not a good idea but I'm a newbie with jQuery and don't really know how to fix it. Thanks for the answers.
function setState(id) { switch (id) { case 1: { break; } case 2: { break; } case 3: { break; } case 4: { break; } case 5: { break; } case 6: { break; } } } $('#button-menu').find('span').each.(function(){ $(this).on("click", (function(){ setState($(this).data("id")) })) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="button-icon" id="button-menu"> <span data-id="1">Option1</span> <span data-id="2">Option2</span> <span data-id="3">Option3</span> <span data-id="4">Option4</span> <span data-id="5">Option5</span> <span data-id="6">Option6</span> </div>
The main issue with your code is that the .
after each
is causing a syntax error. You can see this in the console. Note that this should be the first place you check whenever some JS code does not work as you expect it to. In most browsers this can be opened by pressing F12
There are also several other things you can do to improve the logic:
find()
and just select the #button-menu span
elements directly each()
entirely. You can add event handlers on a collection of elements as a group ()
function setState(id) { switch (id) { case 1:{ console.log('one'); break; } case 2: { console.log('two'); break; } case 3: { console.log('three'); break; } case 4: { console.log('four'); break; } case 5: { console.log('five'); break; } case 6: { console.log('six'); break; } } } $('#button-menu span').click(function() { setState($(this).data("id")); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="button-icon" id="button-menu"> <span data-id="1">Option1</span> <span data-id="2">Option2</span> <span data-id="3">Option3</span> <span data-id="4">Option4</span> <span data-id="5">Option5</span> <span data-id="6">Option6</span> </div>
There is no need for the .each function, because jQuery abstracts it for you...
You can simply $('#button-menu').find('span').on('click', func...
And jQuery will apply the event to every button that the selector returns.
The more simple route to take is using Event Delegation . Which simply means placing a click handler on the container element and capturing all child events that bubble to the top ie. Event Bubbling . Quick example below :
button-menu
is your container element in this case...
$("#button-menu").on('click', function(e){
let id = $(e.target).data("id");
setState(id);
console.log(id);
});
Hope this helps.
remove the "." after "each" and you are fine.
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.