如何在jQuery中找到最接近的兄弟

时间:2017-01-12 19:20:12

标签: javascript jquery dom-traversal

我正在尝试学习jQuery,我有以下标记

在div中,我有两个文本日期和描述以及两个按钮编辑和删除。

当我点击编辑按钮时,我想获得该div的日期和描述

此处我尝试使用parents()选择器,如何在此处使用closest()选择器,如果当前标记无法使用,请建议我如何继续{{1}选择器。



closest()

$(document).ready(function() {
  //If i click on edit button . I want to select the corresponding date and description .How can we do that?

  $(".taskTemplate .edit").on('click', function(event) {
    editTask(event.target);
  });
});

function editTask(node) {

  var date = $(node).parents('.taskTemplate').find('.date').html();
  alert(date);
}




请帮忙

由于

2 个答案:

答案 0 :(得分:2)

只需在parents()中将closest()替换为:

var date = $(node).closest('.taskTemplate').find('.date').html();

希望这有帮助。



$(document).ready(function() {
  $(".taskTemplate .edit").on('click', function(event) {
      editTask(event.target);
  });
});

function editTask(node) {
  var closest_div = $(node).closest('.taskTemplate');
  
  var date = closest_div.find('.date').text();
  var description = closest_div.find('.desc').text();

  console.log(date, `|`, description);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="taskTemplate">
  <span class="date">205-10-09</span>
  <span class="desc">description of task</span>
  <input type="button" class="edit" value="edit">
  <input type="button" class="delete" value="delete">
  <span class="done">done</span>
</div>

<div class="taskTemplate">
  <span class="date">2015-11-19</span>
  <span class="desc">description of task2</span>
  <input type="button" class="edit" value="edit">
  <input type="button" class="delete" value="delete">
  <span class="done">done</span>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

  

当我点击编辑按钮时,我想获取日期和说明   那个div

您可以使用.siblings()选择.date .desc兄弟.edit元素

$(document).ready(function() {
  //If i click on edit button . I want to select the corresponding date and description .How can we do that?

  $(".taskTemplate .edit").on('click', function(event) {
    editTask($(this).siblings(".date, .desc"));
  });
});

function editTask(nodes) {
 var data = $.map(nodes, function(el) {
    return `${el.className}: ${el.textContent}`
  }).join(", ");

  alert(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="taskTemplate">
  <span class="date">205-10-09</span>
  <span class="desc">description of task</span>
  <input type="button" class="edit" value="edit">
  <input type="button" class="delete" value="delete">
  <span class="done">done</span>
</div>

<div class="taskTemplate">
  <span class="date">2015-11-19</span>
  <span class="desc">description of task2</span>
  <input type="button" class="edit" value="edit">
  <input type="button" class="delete" value="delete">
  <span class="done">done</span>
</div>