使用on()方法获取当前对象

Get current object with the on() method

本文关键字:对象 获取 方法 on 使用      更新时间:2023-09-26

如何更新调用事件"change"的当前行的特定输入?

这是我的脚本:

$('#absence-table').on('change', '.from input, .to input',function() {
    var from   = $('.from input').val();
    var to     = $('.to input').val();
    if (from != "" && to != "")
    {
        d1 = getTimeStamp(from);
        d2 = getTimeStamp(to);
        if(d1 <= d2)
        {
            $('.result input').val(new Number(Math.round(d2 - d1)+1));
        }
        else
        {
            $('.result input').val(0);
        }
    }
});

HTML:

<table class="table table-bordered" id="absence-table">
<tr>
    <th>Absence type</th>
    <th>From</th>
    <th>To</th>
    <th>Days requested</th>
    <th>Morning</th>
    <th>Afternoon</th>
    <th colspan="2">Comment</th>
</tr>
<tr class="main-abs-line">
    <td>
        <select name="absence-type" class="input-small">
            <option value="t1">type1</option>
            <option value="t2">type2</option>
        </select>
    </td>
    <td class="from"><input type="text" class="input-small" /></td>
    <td class="to"><input type="text" class="input-small" /></td>
    <td class="result"><div class="text-center"><input type="text" class="input-xsmall" /></div></td>
    <td class="morning"><div class="text-center"><input type="checkbox"></div></td>
    <td class="afternoon"><div class="text-center"><input type="checkbox"></div></td>
    <td colspan="2"><input type="text" /></td>
</tr>
// some tr added by the append() method

当前,只有第一行的结果输入被更新,当前结果输入是从第一行复制的。这很奇怪,因为".from input"answers".to input"中的值是正确的(当前行的值)。

通常我使用$(this)来获取当前对象,但使用on()方法我不知道该怎么做

我相信这就是您想要的:

$('#absence-table').on('change', '.from input, .to input',function() {
    $tr = $(this).closest("tr");
    var from   = $tr.find('.from input').val();
    var to     = $tr.find('.to input').val();
    if (from != "" && to != "")
    {
        d1 = getTimeStamp(from);
        d2 = getTimeStamp(to);
        if(d1 <= d2)
        {
            $tr.find('.result input').val(new Number(Math.round(d2 - d1)+1));
        }
        else
        {
            $tr.find('.result input').val(0);
        }
    }
});

这假设您有几个包含.to.from.resulttr,并且当更新.to.from时,您希望更新同一tr中的.result

您可以通过传递事件来使用event.target来实现

实时演示

function(event){
  alert(event.target.id);

你的代码是

$('#absence-table').on('change', '.from input, .to input',function(event) {
   alert(event.target.id);
   //your code
});

如果(根据您的评论)您想要为触发change事件的任何元素提供封闭的tr,只需使用:

var $tr = $(this).closest('tr');

在事件处理程序中,this对应于触发元素,即使使用委托的事件处理程序也是如此。