如何使用正则表达式按名称选择元素

How to select elements by name using RegEx

本文关键字:选择 元素 何使用 正则表达式      更新时间:2023-09-26

>我有一个包含一些记录的表,在tr的每一行中,我有两个文本框,分为两个TD,所有的文本框都没有IdClass,它们只有一个Name,它们的名字如下

PurchaseDetails[some number].Quantity
PurchaseDetails[some number].PurchasePrice

喜欢:

PurchaseDetails[1457160526936].Quantity
PurchaseDetails[1457160526936].PurchasePrice

我使用以下代码,但不起作用:

var ProductQuantity = $(this).find("input[name=PurchaseDetails[/^[0-9]+$/].Quantity]").val();
var ProductPurchase = $(this).find("input[name=PurchaseDetails[/^[0-9]+$/].PurchasePrice]").val();

我的完整 HTML 代码是:

 <tr >                                                        
 <td><input type="text" class="form-control" name="PurchaseDetails[1457161853893].Quantity" ></td>
 <td><input type="text" class="form-control" name="PurchaseDetails[1457161853893].PurchasePrice" ></td>
 </tr>

如果在当前上下文中只有一个具有该前缀和后缀的元素($(this) ),则可以使用属性以选择器开头,属性以选择器结尾。

$(this)
    .find('input[name^="PurchaseDetails"][name$="Quantity"]').val();

您可以使用filter()通过正则表达式进行过滤

// replace `$('input')` to `$(this).find('input')` to avoid searching in global context
var ProductQuantity = $("input").filter(function() {
  return /^PurchaseDetails'['d+']'.Quantity$/.test(this.name);
}).val();
var ProductPurchasePrice = $("input").filter(function() {
  return /^PurchaseDetails'['d+']'.PurchasePrice$/.test(this.name);
}).val();
console.log(ProductQuantity, ProductPurchasePrice);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="PurchaseDetails[1457160526936].Quantity" value=1 />
<input name="PurchaseDetails[1457160526936].PurchasePrice" value=2 />