Javascript 如何在最近的标记中查找类?

Javascript 如何在最近的标记中查找类?,javascript,Javascript,如何使用Java脚本在最近的标记中查找类?需要在中找到“客户”类。示例如下: <tr> <td class="customer"> @Html.DisplayFor(modelItem => item.Cust) </td> <td> <select id="

如何使用Java脚本在最近的标记中查找类?需要在中找到“客户”类。示例如下:

       <tr>
            <td class="customer">
                @Html.DisplayFor(modelItem => item.Cust)
            </td>
            <td>
                <select id="decisionList">
                    <option value="0" selected></option>
                    <option value="1">None</option>
                </select>
            </td>
       </tr>

我想这就是你想要的:

document.querySelector("#decisionList").addEventListener('change', function() {
  const selectedOptionIndex = this.options[this.selectedIndex].index;
  const invoiceDateText = this.closest('tr').querySelector('.customer').textContent;
});

我想这就是你想要的:

document.querySelector("#decisionList").addEventListener('change', function() {
  const selectedOptionIndex = this.options[this.selectedIndex].index;
  const invoiceDateText = this.closest('tr').querySelector('.customer').textContent;
});

最近的
方法使用
查询选择器
查找最近的

var invoiceDateText=this.closest('.customer').textContent;
然后,它应该向文档根搜索
DOM
,以查找与customer类最接近的元素

如果您想用
customer
类的单元格搜索最近的
tr
,您可以将其修改为

var invoiceDateText=this.closest('tr>.customer').textContent;

最近的
方法使用
查询选择器来查找最近的

var invoiceDateText=this.closest('.customer').textContent;
然后,它应该向文档根搜索
DOM
,以查找与customer类最接近的元素

如果您想用
customer
类的单元格搜索最近的
tr
,您可以将其修改为

var invoiceDateText=this.closest('tr>.customer').textContent;

Swap
find
querySelector
?Swap
find
querySelector
?我应该使用const还是var?有什么显著的区别吗?@Muska是的。这是有区别的。我应该使用const还是var?有什么显著的区别吗?@Muska是的。这是有区别的。