使用 jquery 在最近的单元格 (td) 中查找元素?

Find an element in the nearest cell (td) using jquery?

下面是一个函数,当输入值B时转换值A,反之亦然。

我正在尝试找到一种有效的方法来使用 javascript 或 [=] 仅 最接近的匹配输入33=]jQuery.

我试过了jQuerysiblings, closest, prev and find.

问题

使用 Javascript 定位相邻单元格中的元素而不会使搜索功能变得复杂的有效方法是什么?


DEMO

HTML

<td><input class="A" value="0" OnChange="convertA(this.id, this.value);"/></td>
<td><input class="B" value="0" OnChange="convertB(this.id, this.value);"/></td>

JQUERY

function convertA(id, value) {
    $('.B').val(value * 2);
}
function convertB(id, value) {
    $('.A').val(value / 2);
}

仅使用 jquery

$("input").change(function() {
    var n = this.value;
    if ($(this).hasClass("B")) {
        n = this.value / 2;
    } else {
        n = this.value * 2;
    }
    $(this).closest("td").siblings().find("input").val(n);
});

Fiddle

*

您的主要问题是因为当您通过属性附加事件处理程序时,this 关键字没有引用引发事件的元素。您可以通过在 JS 中附加您的事件来解决这个问题。

然后您可以使用 closest() 查找父 tr 元素,并 find() 在该行中找到相关的 input。试试这个:

<tr>
    <td><input class="A" value="0" /></td>
    <td><input class="B" value="0" /></td>
</tr>
$('.A').change(function() {
    var id = this.id;
    var value = this.value;
    $(this).closest('tr').find('.B').val(value * 2);
});

$('.B').change(function() {
    var id = this.id;
    var value = this.value;
    $(this).closest('tr').find('.A').val(value / 2);
});

Updated fiddle

因为您正在使用 jQuery 也将其用于事件句柄

jQuery(function($) {
  //use jQuery event handlers
  $('.A').change(function() {
    //find the element in the same row and update
    $(this).closest('tr').find('.B').val((this.value / 2) || 0)
  });
  $('.B').change(function() {
    $(this).closest('tr').find('.A').val((this.value * 2) || 0)
  });
})
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<table>
  <tr>
    <td>
      <input class="A" value="0" />
    </td>
    <td>
      <input class="B" value="0" />
    </td>
  </tr>
  <tr>
    <td>
      <input class="A" value="0" />
    </td>
    <td>
      <input class="B" value="0" />
    </td>
  </tr>
</table>

以相邻单元格中的元素为目标的最有效方法是使用 .next() 方法...

你可以试试这个:

$(document).ready(function(){
    $(".A").on("input", function(){
        $(this).closest("tr").find("input.B").val(eval($(this).val()*2));
    });
    $(".B").on("input", function(){
        $(this).closest("tr").find("input.A").val(eval($(this).val()/2));
    });
});

DEMO

$(".A, .B").on("keyup", function(){
    $(this).hasClass("A") ? $(this).closest("tr").find(".B").val(this.value * 2) : 
                            $(this).closest("tr").find(".A").val(this.value / 2);
});

jsFiddle here

但最好使用更具体的 class names/identifiers。