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.
4 Respuestas
+ 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';
}
+ 1
Thank you two for the quick answers.
Especially to you KrOW for the explanation. Now I understood that too! THX
+ 1
👍👍👍