组合执行相同类型操作的函数

时间:2014-11-07 22:01:33

标签: javascript jquery

我有两个功能可以执行几乎相同的任务,但是在不同的元素上。我只想到我会有两个,但现在我计划增加更多,所以我注意到会有很多冗余。我该怎么做才能改进我的jQuery?

$('input#activity-view').change(function() {
    if (this.checked) {
        $('.action-view').show();
    } else {
        $('.action-view').hide();
    }
});

$('input#activity-upload').change(function() {
    if (this.checked) {
        $('.action-upload').show();
    } else {
        $('.action-upload').hide();
    }
});

HTML是这样的:

<input type="checkbox" id="activity-view"> View<br />
<input type="checkbox" id="activity-upload"> Upload<br />
<br />
<div class="action-upload">test</div>
<div class="action-upload">abc</div>
<div class="action-view">kk</div>
<div class="action-upload">yes</div>

jsFiddle http://jsfiddle.net/rLs82of1/

5 个答案:

答案 0 :(得分:1)

&#13;
&#13;
$(':checkbox[id^="activity-"]').on('change', function() {
  var sel = '.action-' + this.id.split('-').pop();
  $(sel)[ this.checked ? 'show' : 'hide' ]();
})
.change();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="activity-view"> View<br />
<input type="checkbox" id="activity-upload"> Upload<br />
<br />
<div class="action-upload">test</div>
<div class="action-upload">abc</div>
<div class="action-view">kk</div>
<div class="action-upload">yes</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

组合选择器,用逗号分隔

$('input#activity-upload, input#activity-view').change(function() {

当然,你必须要检查以确保隐藏/显示正确的分类元素

答案 2 :(得分:0)

只需像这样改变你的选择

$('input#activity-view,input#activity-upload').change( /* … */

http://jsfiddle.net/rLs82of1/1/

答案 3 :(得分:0)

尝试

var handleChange = function(elem, el) {
    var elem = $(elem), el = $(el);
    elem.change(function() {
        if (this.checked) {
            el.show();
        } else {
            el.hide();
        }
    });
};

handleChange('input#activity-view', '.action-view');
handleChange('input#activity-upload', '.action-upload');

jsfiddle http://jsfiddle.net/guest271314/xtm7n0hj/

答案 4 :(得分:0)

您可以尝试为输入id和divs类设置相同的名称,然后只需:

$('input').change(function(){
    var id = $(this).attr('id');
    if(this.checked){
        $('.' + id).show();
    }else{
        $('.' + id).hide();
    }
});

http://jsfiddle.net/rLs82of1/6/