I’ve been using Jquery for some time now and I have a question concerning bad/good practices. Here is the deal. Lets say we have this HTML:
<span class='а_s_trigger' id='tekst1'>text1</span> <span class='а_s_trigger' id='video1'>video1</span> <div class='a_s_songvideo' id='showvideo1'> <object> //video1 </object> </div> <div class='a_s_songtext' id='showtext1'> <p> //text1 </p> </div>
And the following jQuery function that triggers hide/show on click for an element that is either video or text.
$('.а_s_trigger') .bind('mouseover',function(e) { $(this).css({background:'#F3F3F3',cursor:'pointer'}); }) .bind('mouseout',function(e) { $(this).css({background:'#E6E6E6'}); }) .bind('click',function(e) { var id=$(this).attr('id'); var status=$(this).attr('id').toString().slice(0,5); var index=$(this).attr('id').toString().slice(5,7); var visibility=$('#showtext'+index).css('display'); if(status=='tekst1') { if(visibility=='block') { $('#showtext'+index).slideUp(); } else if(visibility=='none') { $('#showtext'+index).slideDown(); } } else if(status=='video') { $('#showvideo'+index).toggle(); } });
Everything is working fine but what bugs me is the way I select the element I need :
var id=this.id; var status=$(this).attr('id').toString().slice(0,5); var index=$(this).attr('id').toString().slice(5,7); var visibility=$('#showtext'+index).css('display');
Is it OK to assign variables to strings in such manner? I know that jQuery is all about selectors and the nice chaining functions like :
$(this).children().siblings().attr('id'); //and so on
Should I always try to select elements using the chain selectors or should I follow the principle ‘If it works don’t change it!’?
I’m a Class man
To me its much easier and you can grab multiple elements, but if you have no problem with your way as you said