3

我这里有这段代码,它为复选框提供了一个进度条。我想在单页中使用多个这样的进度条。如何为每个 div 唯一地调用函数?

$(window).load(function(){
$(function() {
    $("#remind").progressbar({
        value: 0,
        max: 100,
        textFormat: 'fraction',
        complete: function(event, ui) {
            alert("Job complete you lazy bum!");
        }
    });

    $('.option').on('change', function() {
        var total = 0;

        $('.option:checked').each(function() {
            total += parseInt($(this).val());
        });

        $("#remind").progressbar("value", total);
    });

});
});

这是html部分,

<div id="remind"></div>  
<div>
    <input type="checkbox" class="option" value="25"> Task 1<br>
    <input type="checkbox" class="option" value="25"> Task 2<br>
    <input type="checkbox" class="option" value="25"> Task 3<br>
    <input type="checkbox" class="option" value="25"> Task 4<br>
</div>

我如何让另一个具有相同功能的 div 工作而不会干扰另一个,但又不编写所有更改类和 id 名称的 js。

4

2 回答 2

1

好吧,如果持有选项的 div 始终遵循进度条 div,您可以在脚本中使用此连接,(应该使用以 + 开头的行而不是带有 - 的行)

而不是 id 使用类“提醒”:

+<div class="remind"></div> 
-<div id="remind"></div>

按类而不是 id 初始化进度条:

+$(".remind").progressbar({
-$("#remind").progressbar({

对父级 (div) 中的其他选中选项使用本地化搜索:

+$(this).parent().find('.option:checked').each(function() {
-$('.option:checked').each(function() {

最后使用 HTML 结构增加 prev div 选项的进度:
*here 扮演我回答的第一句他的角色

+$(this).parent().prev('div.remind').progressbar("value", total);
-$("#remind").progressbar("value", total);

欢迎来到stackoverflow![:

这是一个jsFiddle 可以看到它的工作原理。

于 2012-11-10T19:56:32.793 回答
1

您必须将它们包装在一个容器中并使用它来关联它们,或者更好地为input元素提供一个data-将它们与其进度条相关联的属性。

html

<div id="remind" class="progress-bar"></div>  
<div>
    <input type="checkbox" class="option" value="25" data-progress="remind"> Task 1<br>
    <input type="checkbox" class="option" value="25" data-progress="remind"> Task 2<br>
    <input type="checkbox" class="option" value="25" data-progress="remind"> Task 3<br>
    <input type="checkbox" class="option" value="25" data-progress="remind"> Task 4<br>
</div>
<div id="forget" class="progress-bar"></div>  
<div>
    <input type="checkbox" class="option" value="25" data-progress="forget"> Task 1<br>
    <input type="checkbox" class="option" value="25" data-progress="forget"> Task 2<br>
    <input type="checkbox" class="option" value="25" data-progress="forget"> Task 3<br>
    <input type="checkbox" class="option" value="25" data-progress="forget"> Task 4<br>
</div>

jQuery

$(".progress-bar").progressbar({
    value: 0,
    max: 100,
    textFormat: 'fraction',
    complete: function(event, ui) {
        alert("Job complete you lazy bum!");
    }
});

$('.option').on('change', function() {
    var total = 0,
        progressbarID = $(this).data('progress');

    $('input[data-progress="'+progressbarID+'"].option:checked').each(function() {
        total += parseInt($(this).val());
    });

    $('#'+progressbarID).progressbar("value", total);
});

演示在 http://jsfiddle.net/kksXU/

于 2012-11-10T20:02:59.397 回答