0

我有一个无序列表的链接,它们都对应于我的 JS 文件中的不同事件。现在我正在使用

$('#gst').click(function(){
    preset(gst);
});
$('#gsd').click(function(){
    preset(gsd);
});
$('#ts').click(function(){
    preset(ts);
});
$('#none').click(function(){
    preset(none);
});

这是我的预设功能:

function preset(setter){
if(setter === gst){
    currentPreset = gTitle;
    $('#count').html(currentPreset);
}else if(setter === gsd){
currentPreset = gDesc;
}else if(setter === ts){
currentPreset = tLimit;
}else{
currentPreset = none;
$('#count').html(currentPreset);
}
}

它看起来很可怕。我知道有一种“干”的方法可以做到这一点。但我还没有找到一个。有谁知道做到这一点的最佳方法?这一定非常棒!

谢谢

4

3 回答 3

4
$("#gst, #gsd, #ts, #none").click(function(){
    preset(this.id);
});
于 2013-01-27T22:25:58.647 回答
3
function handleClick() {
    preset(window[$(this).attr('id')]);
}

$('#gst, #gsd, #ts, #none').click(handleClick);
于 2013-01-27T22:26:15.500 回答
1

使预设以字符串为参数,然后按照以下方式执行操作

$('.classGivenToAll').click(function() {
    preset($(this).attr("id"));
});

如果您想切换到任何其他属性,我会以这种方式获取 id。

于 2013-01-27T22:26:08.280 回答