如何优化此javascript代码? [英] how to optimize this javascript code?
本文介绍了如何优化此javascript代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何优化此功能?我可以为所有操作设定一个功能吗?
How to optimize this functions? Can I make one function for all operations?
$('#b-hat1').click(function() {
$('#hat3').hide();
$('#hat2').hide();
$('#hat1').show();
});
$('#b-hat2').click(function() {
$('#hat3').hide();
$('#hat2').show();
$('#hat1').hide();
});
$('#b-hat3').click(function() {
$('#hat3').show();
$('#hat2').hide();
$('#hat1').hide();
});
推荐答案
没有您的html,我只能给您一个有关如何解决它的想法".
Without your html, i can only give you a "rought" idea about how to solve it.
$("div[id^='hat']").hide();
隐藏所有以hat
$('div[id^="b-hat"]').click(function() {
var id = $(this).attr("id").replace("b-","");
$("div[id^='hat']").hide();
$('#' + id).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hat1">hat1</div>
<div id="hat2">hat2</div>
<div id="hat3">hat3</div>
<br><br>
<div id="b-hat1">Show hat1</div>
<div id="b-hat2">Show hat2</div>
<div id="b-hat3">Show hat3</div>
这篇关于如何优化此javascript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文