gpt4 book ai didi

javascript - 表格单元格文本不更新文本内容

转载 作者:行者123 更新时间:2023-11-30 21:05:20 25 4
gpt4 key购买 nike

我有一个基本的 parking 计算器。它通过在包裹上使用来计算所需的空间。

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

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

此外,如果您不从第一行开始,则不会显示单位。

基本上,当用途改变时,我会在该行中找到带有类的 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 示例,链接如下,你可以看到这个。要进行测试,请为第一个表格行选择一个用途。然后设置下。单位将匹配。然后将第一行更改为不同的内容。然后所有单位都会在更改时匹配。

fiddle

最佳答案

这个选择器:

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

正在选择该类的第一个实例。像这样正确地确定范围:

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

作为旁注,最好缓存 $(this),因为您不止一次使用它:

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

这是 a working fiddle .

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

$(".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 .

关于javascript - 表格单元格文本不更新文本内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46690883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com