javascript - 更改 div 数组中衣柜 div 的文本

标签 javascript jquery

我有以下 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/

相关文章:

javascript - Jquery 侧边栏滑出/滑入无法在本地工作

javascript - 如果在 span 中显示特定文本,则隐藏 div

javascript - 无法捕获 youtube Crossrider 扩展中修改的 DOMSubtree

jquery - 正则表达式/替换问题如何在查询中搜索文本时删除

javascript - Chrome 无法识别 24 :00:00 while Firefox does

如果单击子节点,则不会触发 JavaScript 单击事件

javascript - Jquery Enable button on click div 并显示相应的元素

ajax - Jquery Ajax如何从ResponseBody获取数据?

c# - 使用 List<> 作为模型 - asp.net mvc

jquery - x-可编辑远程源的过程响应