将多个相同的功能简化为一个

时间:2014-12-01 10:02:23

标签: jquery

这里是jquery的新手。我有如下功能,但我非常确定这是一种缩短方法的简洁方法。我该如何简化这个?

var checkAttr1 = div.attr('data-featureid-1')
var checkAttr2 = div.attr('data-featureid-2')
var checkAttr3 = div.attr('data-featureid-3')
var checkAttr4 = div.attr('data-featureid-4')
var checkAttr5 = div.attr('data-featureid-5')
var checkAttr6 = div.attr('data-featureid-6')
var checkAttr7 = div.attr('data-featureid-7')
var checkAttr8 = div.attr('data-featureid-8')
var checkAttr9 = div.attr('data-featureid-9')
var checkAttr10 = div.attr('data-featureid-10')

if(checkAttr1){$('.tickee[data-tickid="1"]').css('display','block')}
if(checkAttr2){$('.tickee[data-tickid="2"]').css('display','block')}
if(checkAttr3){$('.tickee[data-tickid="3"]').css('display','block')}
if(checkAttr4){$('.tickee[data-tickid="4"]').css('display','block')}
if(checkAttr5){$('.tickee[data-tickid="5"]').css('display','block')}
if(checkAttr6){$('.tickee[data-tickid="6"]').css('display','block')}
if(checkAttr7){$('.tickee[data-tickid="7"]').css('display','block')}
if(checkAttr8){$('.tickee[data-tickid="8"]').css('display','block')}
if(checkAttr9){$('.tickee[data-tickid="9"]').css('display','block')}
if(checkAttr10){$('.tickee[data-tickid="10"]').css('display','block')}

2 个答案:

答案 0 :(得分:0)

将一个类设置为所有div,然后使用.each()函数

$.each('classname', function(){
    $(this).css('display', 'block')
});

答案 1 :(得分:0)

使用循环。试试这个:

for (var i = 1; i <= 10; i++) {
    setDisplay(div, i);
}

function setDisplay(div, i) {
    if (div.attr('data-featureid-' + i)
        $('.tickee[data-tickid="' + i + '"]').css('display', 'block');
}