0

JQuery ? And : in function

Hello everyone, I found a jQuery code on the internet that I don't quite understand. $('img').on({ 'click': function() { var src = ($(this).attr('src') === 'img1_on.jpg') ? 'img2_on.jpg' : 'img1_on.jpg'; $(this).attr('src', src); } }); I am concerned here with the pictures and in particular with the spelling with ? And : Unfortunately I couldn't find an explanation either.

10th Jan 2019, 2:37 PM
Carsten
Carsten - avatar
4 ответов
+ 6
Its the ternary conditional operator... In practice its a brief form of if/else construct with some limitations (its used only for return a value with a condition). The form is: condition? value_on_true : value_on_false In your example its like: if($(this).attr('src')==='img1_on.jpg'){ src= 'img2_on.jpg'; }else{ src= 'img1_on.jpg'; }
10th Jan 2019, 3:00 PM
KrOW
KrOW - avatar
10th Jan 2019, 2:56 PM
Dennis
Dennis - avatar
+ 1
Thank you two for the quick answers. Especially to you KrOW for the explanation. Now I understood that too! THX
10th Jan 2019, 3:35 PM
Carsten
Carsten - avatar
+ 1
👍👍👍
10th Jan 2019, 6:42 PM
KrOW
KrOW - avatar