2017-10-11 88 views
1

我有一个基本的停车计算器。它通过在包裹上使用计算所需的空间。表格单元格文字没有更新文字内容

我想根据用途更新“单位”。例如,咖啡店单位是杯子而办公室空间是平方英尺。 - 愚蠢的例子。

这似乎只适用于第一行,然后每行都卡在这个单位。

另外,如果你没有从第一行开始单位不显示。

基本上,当使用改变时,我找到该行中的类与td。然后更新适当的单元格。让我知道你是否需要更多的代码。

$(".useType").change(function() { 

    var use = $('.useType').val(); 
    var units = $(this).closest('tr').find('.units'); 
    units.addClass('highlight'); 

    if (use == "General Office 25000sf") { 
    units.text('sf'); 


    } else if (use == "General Retail") { 
    units.text('aisles'); 


    } else if (use == "Fitness Studio") { 
    units.text('weights'); 


    } else if (use == "Coffee Shop") { 
    units.text('cups'); 


    } else if (use == "Restaurant (no bar)") { 
    units.text('plates'); 


    } 


}); 

我已经提出了一个小提琴的例子,下面的链接,你可以看到这个。要进行测试,请为第一个表格行选择一个用途。然后设置下一个。单位将匹配。然后将第一行更改为不同的内容。然后所有的单位都会在更改时匹配。

fiddle

回答

1

此选择:

var use = $('.useType').val(); 

与该类选择的第一个实例。正确的范围是这样的:

let $this = $(this); 
let use = $this.val(); 
let units = $this.closest('tr').find('.units'); 

这里的a working fiddle

var use = $(this).val(); 

作为一个侧面说明,它,因为你使用它不止一次将是更好的缓存$(this)

最后,如果您只是简单地将您的值存储在各种查找中,那么您的代码可以大大简化(并且更具可读性)。这还允许您在不添加其他逻辑的情况下更改/删除任何值。

$(".useType").change(function() { 
    let $this = $(this); 
    let lookup = { 
    "General Office 25000sf": "sf", 
    "General Retail": "aisles", 
    "Fitness Studio": "weights", 
    "Coffee Shop": "cups", 
    "Restaurant (no bar)": "plates" 
    }; 

    $this.closest('tr') 
    .find('.units') 
    .text(lookup[$this.val()]) 
    .addClass('highlight'); 
}); 

这是a working fiddle

+1

非常感谢詹姆斯!这是我错过的一件简单/明显的事情。我也很感激你的快速,有益和非常好的回应。我会在允许的情况下接受。 –

+0

@ Eric.18忍受我一秒钟 - 发布更新的代码。 –

相关问题