我有几个js函数为不同的div做同样的宽度不同的值。这是HTML代码:
<input id="kunst_radio1" type="radio" name="kunstmuseum" value="0" checked="checked" onClick="animateKunst('null')"><label for="kunst_radio1"></label>
<input id="kunst_radio2" type="radio" name="kunstmuseum" value="6794200" onClick="animateKunst('halb')"><label for="kunst_radio2"></label>
<input id="kunst_radio3" type="radio" name="kunstmuseum" value="13588400" onClick="animateKunst('voll')"><label for="kunst_radio3"></label>
<input id="hist_radio1" type="radio" name="hist" checked="checked" onClick="animateHist('null')"><label for="hist_radio1"></label>
<input id="hist_radio2" type="radio" name="hist" onClick="animateHist('halb')"><label for="hist_radio2"></label>
<input id="hist_radio3" type="radio" name="hist" onClick="animateHist('voll')"><label for="hist_radio3"></label>
我有大约15个单选按钮组,对于每个组,我必须使用不同的值执行此功能:
function animateKunst(val) {
var div = $('#kunstmuseum');
if(div.data('originalWidth') == undefined)
div.data('originalWidth', div.width());
var width = div.data('originalWidth');
if (val=="voll")
width *= .6;
else if (val=="halb")
width *= .8;
$('#kunstmuseum').animate({width: width}, 500);
}
function animateHist(val) {
var div = $('#historisch');
if(div.data('originalWidth') == undefined)
div.data('originalWidth', div.width());
var width = div.data('originalWidth');
if (val=="voll")
width *= .7;
else if (val=="halb")
width *= .9;
$('#historisch').animate({width: width}, 500);
}
我可以将所有值放在数组中然后进行for循环吗?我怎样才能做到这一点?
答案 0 :(得分:4)
我会略微修改id,以便我可以在函数中更轻松地重用它们,并为宽度定义映射。
<script type="text/javascript">
var mapping = {
kunst: {
voll: 0.6,
halb: 0.8
},
hist: {
voll: 0.7,
halb: 0.9
},
null: {
voll: 0,
halb: 0
}
};
function animate(type, val) {
var div = $('#' + type);
if ( !div.data('originalWidth') ) {
div.data('originalWidth', div.width());
}
var width = div.data('originalWidth');
width *= mapping[type][val];
div.animate({ width: width }, 500);
}
</script>
<input id="kunst_radio1" type="radio" name="kunst" value="0" checked="checked"
onClick="animate('kunst', 'null')">
<label for="kunst_radio1"></label>
<input id="kunst_radio2" type="radio" name="kunst" value="6794200"
onClick="animate('kunst', 'halb')">
<label for="kunst_radio2"></label>
<input id="kunst_radio3" type="radio" name="kunst" value="13588400"
onClick="animate('kunst', 'voll')">
<label for="kunst_radio3"></label>
<input id="hist_radio1" type="radio" name="hist" checked="checked"
onClick="animate('hist', 'null')">
<label for="hist_radio1"></label>
<input id="hist_radio2" type="radio" name="hist"
onClick="animate('hist', 'halb')">
<label for="hist_radio2"></label>
<input id="hist_radio3" type="radio" name="hist"
onClick="animate('hist', 'voll')">
<label for="hist_radio3"></label>