我有以下 html
<div class="form-group col-md-2 border">
<label for="month">Month 1 - 01/11/2019</label>
<input type="text" class="form-control" id="inputCity[]" name="inputCity[]" value="550">
<label for="Costs">Costs</label>
<input type="text" class="form-control" id="inputcosts" name="costs" value="0">
<label for="grossprofit"><b>Gross Profit</b></label><div id="grossp[]"></div>
</div>
我正在尝试使用以下内容根据输入到 inputcosts 框中的内容更改grossp[] 文本
$(document).on('change keydown paste input', '#inputcosts' , function() {
var monthcalc = $(this).closest("input[name='inputCity[]']").val();
var gcost = monthcalc - this.value;
$(this).closest("div[id='grossp[]']").html(gcost);
});
div 没有更新,也没有错误消息。
有什么想法吗?
最佳答案
作者:documentation , .closest
检查自己和所有 parent
<小时/>For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree
这是因为 #grossp[]
不是 inputcosts
的父级。
首先选择父级,然后执行.find
$(this).closest('.form-group').find("div[id='grossp[]']")
<小时/>
由于您通过 ID 选择,因此无需查找周围的任何内容,因为 ID 在页面中是唯一的:$('#grossp[]')
根据您的命名id='grossp[]'
,似乎有多个元素具有相同的ID。 这是不可能/无效的。只有 name
属性可以包含 []
以将其作为元素数组提交。任何其他属性都只是纯文本。
关于javascript - 更改 div 数组中衣柜 div 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58960801/