簡體   English   中英

使用$(this)范圍查找上一個父元素

[英]Using $(this) scope to find parent previous element

我有一個HTML看起來像:我正在嘗試獲取當前父對象最近的對象值。 在這種情況下,我嘗試獲取owner_address,owner_name的值。

<div class = "form-group row">
  <div class="col-xs-6 form-group">
      <input id="owner_name" type="text></input>
  </div>
  <div class="col-xs-6 form-group">
      <input id="owner_address" type="text></input>
  </div>
</div>
<div class="form-group row">
   <div class="col-xs-6 form-group">
      <input onclick="runFunction($(this))" id="update" type="text></input>
  </div>

</div>

我嘗試獲取值的JS部分。

<script>
  function runFunction(thisObj){
      var owner_name = thisObj.parent().closest('#owner_name').val()
      #Gives me undefined.
  } 
</script>

我已經嘗試過使用ID選擇它; 在我的情況下,它不起作用,因為數據是在模態內部呈現的; 每個模態都是唯一的 我想在每個唯一模式中獲取特定的所有者名稱; 這就是為什么我認為使用$(this)會很方便的原因。

嘗試這個

     var owner_name = thisObj.parent().parent().closest('.form-group').find('#owner_name).val()

試試這個演示: https : //jsfiddle.net/xianshenglu/4nt42cso/4/

我更改了js,如果您使用id選擇器,則不必使用其他選擇器。

function runFunction(thisObj){
  var owner_name = $('#owner_name').val()
  alert(owner_name);
} 

還要更改您的html,只需更正語法錯誤即可。例如,不應使用以下代碼:</ input> 、、、

    <div class="form-group row">
    <div class="col-xs-6 form-group">
        <input id="owner_name" type="text" />
    </div>
    <div class=" col-xs-6 form-group ">
        <input id="owner_address " type="text" />
    </div>
</div>
<div class="form-group row">
    <div class="col-xs-6 form-group">
        <input onclick="runFunction($(this))" id="update" type="text" />
    </div>
</div>

將其放在您的功能中,並檢查其是否返回所需的值。

thisObj.parent()。parent()。parent()。find(“ #owner_name”).val();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM