jQuery - 如何在特定元素下找到具有部分ID的元素

时间:2017-06-05 21:58:33

标签: jquery

我有多条记录,每条记录都有相同的字段,它们都具有相同的名称/ ID,加上RecordID。当我按下cmdUpdate_xxx时,我会检测到哪个记录div,将其分配给' fldTarget'。我知道要检查每个字段(20,所以不要手动执行此操作)以确保有效性。我试过了

$('#RecordsWrapper')
    .on("click" , "[id*=cmdUpdate]", "input", function(e){
      fldTarget = $(this);
      fldAccountID = fldTarget.parent().find("#txtAccountID").prop("id");`
    })

...但fldAccountID以undefined的形式返回。如何找到包含' txtAccountID'的ID的子元素?在' Record001' DIV?

<div id='RecordsWrapper'>
<div id='Record001'>
  <input type='text' id='txtAccount_001'>
  <input type='text' id='txtEntry_001'>
  <input type='text' id='txtValue_001'>
  <input type='submit' id='cmdUpdate_001'>
</div>
<div id='Record002'>
  <input type='text' id='txtAccount_002'>
  <input type='text' id='txtEntry_002'>
  <input type='text' id='txtValue_002'>
  <input type='submit' id='cmdUpdate_002'>
</div>
</div>

2 个答案:

答案 0 :(得分:3)

使用属性选择器:

  

属性选择器

     

属性选择器使用给定属性或属性值的选择来选择元素。

     

参考:default-mimetype

     

REF(此处更多示例):https://developer.mozilla.org/en/docs/Web/CSS/Attribute_selectors

input[id^=txtAccount] {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='RecordsWrapper'>
  <div id='Record001'>
    <input type='text' id='txtAccount_001'>
    <input type='text' id='txtEntry_001'>
    <input type='text' id='txtValue_001'>
    <input type='submit' id='cmdUpdate_001'>
  </div>
  <div id='Record002'>
    <input type='text' id='txtAccount_002'>
    <input type='text' id='txtEntry_002'>
    <input type='text' id='txtValue_002'>
    <input type='submit' id='cmdUpdate_002'>
  </div>
</div>
SELECT  
ID
  , DeptCode AS 'DC'
  , OpCode AS 'OC' 
  ,Units = sum(Units)
  ,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
  ,Percentage = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0)) / 150 


FROM dbo.TimeLog 
 WITH (NOLOCK)

WHERE DeptCode = 'FB'
  and OpCode   = 'PU'
  and Units IS NOT NULL
GROUP BY 
    ID
  , DeptCode
  , OpCode 

答案 1 :(得分:0)

由于您已经存储了fldTarget中存储的当前记录的div,您可以从该div的自己的ID中解析记录ID吗?

例如。

var recordID = fldTarget.prop('id').replace('Record', '');
var txtAccountID = 'txtAccount_' + recordID;

或者您可以为每个&#34;记录添加data-*属性&#34; div to hold包含ID num,如下所示:

<div id='Record001' data-id="001">
    <input type='text' id='txtAccount_001'>
    <input type='text' id='txtEntry_001'>
    <input type='text' id='txtValue_001'>
    <input type='submit' id='cmdUpdate_001'>
</div>
<div id='Record002' data-id="002">
    <input type='text' id='txtAccount_002'>
    <input type='text' id='txtEntry_002'>
    <input type='text' id='txtValue_002'>
    <input type='submit' id='cmdUpdate_002'>
</div>

从这个属性中获取值:

var recordID = fldTarget.data('id');
var txtAccountID = 'txtAccount_' + recordID;