jQuery遍历。找到自己的兄弟姐妹

时间:2016-11-22 09:26:23

标签: javascript jquery

我正在使用jQuery遍历在DOM元素之间跳转。

首先我有一个onClick功能:

$(document).on('keyup', '.size, .ant', function(){

在此函数内部,我将有关点击内容的数据发送到另一个函数。

sulorTableRowWeight( $(this) );
function sulorTableRowWeight(thisobj){

现在,我想从点击的元素$(this)遍历到其父级。我想找到父母的兄弟姐妹,然后走到一个特定的兄弟姐妹。

var inputSize = $(thisobj).parent().siblings('.sizeTd').children('.size');

我的问题是,当我想要追溯到我来自的元素时,它不会被列为兄弟姐妹,因为它不是兄弟姐妹......

var inputSize = $(thisobj).parent().siblings(); console.log(inputSize)

控制台会给我兄弟姐妹,但不是U来自......

因此,当用户点击“.size”时,我想要遍历父级并返回大小....当用户点击“.ant”时,我想要遍历父级和然后降到“.size”......

我试图对遍历进行硬编码:

var inputSize = $(thisobj).parent().siblings('.sizeTd').children('.size');

但它不起作用,因为它实际上并不是兄弟姐妹。

那是什么?我怎么能回到它?

如果不可能,我必须运行一些if / else语句,猜猜......

更新

$(document).on('keyup', '.size, .ant', function(){ 
  //Find changed <select> .tbody
  var tbodyId = $(this).parent().parent('tr').parent('tbody').attr('id'); 
  //Check <tbody> #id
  if(tbodyId === "cpTableBody"){
  }
  else if(tbodyId === "sulorTableBody"){ 
    sulorTableRowWeight( $(this) );
  }
  else if(tbodyId === "konturTableBody"){
    konturTableRowWeight( $(this) );
  }
  else if(tbodyId === "kantbalkTableBody"){
    kantbalkTableRowWeight( $(this) );
  }
})

//Function sulorTableRowWeight
function sulorTableRowWeight(thisobj){
    //Find the selected data-weight
    var selectedWeightmm3 = $(thisobj).parent().siblings('.selectTd').children('.select').find(':selected').data('weightmm3'); 

    //Find input .size value
    var inputSize = $(thisobj).parent().siblings('.sizeTd').children('.size'); console.log(inputSize)

问题
单击“.size”元素时,我的var inputSize将返回undefined。那是因为它没有被列为自己的兄弟。

我知道这是关键,而不是点击......

3 个答案:

答案 0 :(得分:1)

e.target将选择当前输入

&#13;
&#13;
$(document).on('keyup', '.size, .ant', function(e) {
  inputSize = $(e.target);
  if($(e.target).is('.ant')) {//test if the element is .ant 
  inputSize = $(e.target).parent().find('.size');//get .size based on .ant
  }
   console.log(inputSize[0]);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <input class="size x1" placeholder="x1">
  <input class="ant x1" placeholder="x1 ant">
</div>
<div>
  <input class="size x2" placeholder="x2">
  <input class="ant x2" placeholder="x2 ant">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

嗯,如果你以$(this) thisObj传递thisObj,我认为你不需要在$()中嵌套.parents('<grandparent>').find('<child>')。 (见下面的注释)

无论如何,您可以尝试使用<grandparent>,所以基本上您使用$(this)遍历树上的一个更高级别,然后获取与子选择器匹配的所有后代。这应该包括$代表的三个分支。但是如果没有看到你的HTML,就很难肯定。

**将jQuery对象分配给变量时的一个好习惯是使用var $this = $(this)语法,即$,因此您知道django-models前面的任何内容都是jQuery对象。

答案 2 :(得分:0)

sulorTableRowWeight内,你应该引用thisobj变量中点击的元素。