jQuery Best Practises for HTML Element creation in a specific example
Is there a better way to write the following so that:
a) fewer variables are used that may causes nam开发者_运维问答e collisions?
b) the code is smaller and more maintainable, especially on the line beginning "var $safesurf = $( ' ')" onwards?
var $ratings = [
{
group: 'SS~~001',
name: 'Profanity',
levels: {
'Subtle Innuendo':
'Subtly Implied through the use of Slang',
'Explicit Innuendo':
'Explicitly implied through the use of Slang',
'Technical Reference':
'Dictionary, encyclopedic, news, technical references',
'Non-Graphic-Artistic':
'Limited non-sexual expletives used in a artistic fashion',
'Graphic-Artistic':
'Non-sexual expletives used in a artistic fashion',
'Graphic':
'Limited use of expletives and obscene gestures',
'Detailed Graphic':
'Casual use of expletives and obscene gestures',
'Explicit Vulgarity':
'Heavy use of vulgar language and obscene gestures',
'Explicit and Crude':
'Saturated with crude sexual references and gestures'
}
},
{
group: 'SS~~002',
name: 'Heterosexual Themes',
levels: {
'Subtle Innuendo':
'Subtly Implied through the use of metaphor'
}
}
]
var $safesurf = $( '<div></div> ')
jQuery.each($ratings, function($i, $rating){
var $header = $( '<h3></h3>' )
.append(
$( '<a></a>' )
.attr( 'href', '#' )
.html( $rating.name )
)
var $select = $( '<select></select>' )
.append(
$( '<option></option' )
.html( 'Does not contain this theme' )
)
var $level = 0;
for (var $value in $rating.levels) {
$level++;
$title = $rating.levels[$value];
$select.append(
$( '<option></option>' )
.attr({
title: $title,
value: $rating.group + ' ' + $level
})
.html($value)
.tooltip()
)
}
var $content = $( '<div></div>' )
.append( $select )
$safesurf.append( $header, $content )
})
$safesurf.accordion({
autoHeight: false,
event: 'mouseover'
})
Wrap the entire thing in your own custom jQuery extension to scope your variables and avoid conflicts.
(function($){
$.fn.yourCustomFunctionNameGoesHere = function(arg1, arg2, youGetTheIdea) {
// your code goes here
};
})(jQuery);
精彩评论