简体   繁体   English

如何通过遍历到父div来获取元素的值

[英]How to get the value of an element by traversing to parent div

I am working on a code where i have multiple div's generated dynamically. 我正在处理一个代码,其中我动态生成了多个div。 My problem is to get current hidden elements value on click of a link to that particular div(eg when i click on Add to Favorites it should alert the value of task_for hidden input). 我的问题是在单击指向该特定div的链接时获得当前隐藏元素的值(例如,当我单击“添加到收藏夹”时,它应警告task_for隐藏输入的值)。 My code is working fine with one div but if there is multiple divs it alerts the first element's value. 我的代码在一个div上工作正常,但是如果有多个div,它将警告第一个元素的值。 Here is my code- 这是我的代码-

<div class="col-md-4 col-sm-4 col-xs-12">
<div class="search_box_list">
<a href="javascript:void(0)" class="add_fav"><i class="fa fa-star-o" aria-hidden="true"></i>Add to favourites</a>
<div class="n_s">'+value.user_name+'</div><div class="n_e">'+value.user_email+'</div>
<div class="n_n">'+value.user_phone+'</div>
<div class="n_d">'+value.user_designation+'</div><div class="n_d">
<button type="button" id="assign" class="assign_task" class="btn btn-default">
<input type="hidden" name="for_id" class="task_for" value="'+value.user_id+'" />
<input type="hidden" name="for_id" class="email" value="'+value.user_email+'" /> Assign Task
</button>
</div>
</div>
</div>

and the jquery 和jQuery

$("body").on('click','.add_fav',function(){
  var who_id=<?php echo $_SESSION['global']['uid'] ?>;
  var whom_id=$(document).find(".task_for").val();
  alert(whom_id)
});

Use closest to get the parent .search_box_list and then use find to get the value of the hidden div 使用最接近获取父.search_box_list,然后使用查找获得隐藏div的值

$("body").on('click','.add_fav',function(){
  var who_id  = <?php echo $_SESSION['global']['uid'] ?>;
  var whom_id = $(this).closest('.search_box_list').find(".task_for").val();
  alert(whom_id)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM