How can I simplify this repetitive jquery?
This code lets me display/hide a custom message msg_one
msg_two
msg_three
when the appropriate div is hovered/unhovered over. The appropriate message is injected into the #screen div
and show/hide is then applied. The code is almost identical except for the first 2 lines #one vs #two vs #three
and the message being displayed msg_one msg_two msg_three
.
How can I simplify this into fewer lines of code to get rid of the repetitiveness?
var msg_one = "message 1";
var msg_two = "message 2";
var msg_three = "message 3";
$("#one").hover(function() {
$("#screen").html(msg_one).show();
}, function(){
$("#screen").html("").hide();
});
$("#two").hover(function() {
$("#screen").html(msg_two).show();
}, function(){
$("#screen").html("").hide();
});
$("#three").hover(function() {
$("#screen").html(msg_three).show();
}, function(){
$("开发者_如何转开发#screen").html("").hide();
});
thanks.
You can extend jQuery, like this:
$.fn.hover_message = function (message) {
$(this).bind("hover", function() {
$("#screen").html(message).show();
}, function(){
$("#screen").html("").hide();
});
}
And use the function, like this:
$("#one").hover_message(msg_one);
$("#two").hover_message(msg_two);
$("#three").hover_message(msg_three);
You can put each of the three messages in a title
attribute of the corresponding <div>
. Then you can add a class to the divs and:
$('.hover-div').hover(function() {
var msg = $(this).attr('title');
$("#screen").html(msg).show();
}, function(){
$("#screen").html("").hide();
});
I hope the code works, I wrote it out of my head :). Anyway, the idea is ok.
var msgs = {
'one': 'message 1',
'two': 'message 2',
'three': 'message 3'
}
$('#one, #two, #three').hover(function(){
$("#screen").html(msgs[this.id]).show();
}, function () {
$("#screen").html("").hide();
});
If "#one", "#two", and "#three" are all in the same container, you could take advantage of that:
$("#container").hover(function(e) {
$("#screen").html($(e.target).attr("title")).show();
}, function(e) {
$("#screen").html("").hide();
})
[{elem: '#one', msg: msg_one },
{elem: '#two', msg: msg_two },
{elem: '#three', msg: msg_three }
].each(function(item) {
$(item.elem).hover(function() {
$("#screen").html(item.msg).show();
},
function() {
$("#screen").html("").hide();
});
});
I would create a simple plugin which you can reuse in the long run:
<script type="text/javascript">
(function($){
$.fn.hoverScreen = function(options){
var config = $.extend({}, $.fn.hoverScreen.defaults, options);
return this.each(function(){
var $this = $(this);
$this.hover(function(){
config.screenElem.html(config.text).show();
}, function(){
config.screenElem.html('').hide();
});
});
}
$.fn.hoverScreen.defaults = {
screenElem: null,
text: ''
}
})(jQuery);
</script>
Usage would be now really simple:
$(function(){
$.fn.hoverScreen.defaults.screenElem = $("#screen");
$("#one").hoverScreen({ text: 'message one' });
$("#two").hoverScreen({ text: 'message two' });
});
精彩评论