繁体   English   中英

jQuery遍历。 寻找同胞包括自己

[英]jQuery traversing. Find siblings including itself

我正在使用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”时,我想向上移动到父级,然后向下到“。尺寸”...

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

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。 那是因为它没有被列为自身的同级物。

我知道这是按键,而不是单击...

e.target将选择当前输入

 $(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]); }); 
 <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> 

嗯,如果您要传入$(this)作为thisObj我认为您不需要将thisObj嵌套在$() (请参阅下面的注释)

无论如何,您可以尝试使用.parents('<grandparent>').find('<child>')因此基本上您是在树上使用<grandparent>在更高一级遍历,然后获取与该子级匹配的所有后代选择器。 那应该包括$(this)代表的三个分支。 但是,如果没有看到HTML,很难确定地说。

**将jQuery对象分配给变量时的一个好习惯是使用$语法,即var $this = $(this)因此您知道以$开头的任何东西都是jQuery对象。

sulorTableRowWeight内部,您应该在thisobj变量中具有对clicked元素的引用。

暂无
暂无

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

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