parent()和nearest()如何在jQuery中工作?

时间:2016-03-20 21:32:17

标签: jquery html-table append rows

我想简单地在单击后者row之后添加row表,因此我使用了以下代码(实际上我在visualforce页面中使用了此代码)。

function queryAndUpdateLead() { 
        var a = $('[id$=ibrahim]').closest('tr')
                .after('<tr><td>New Content 1</td><td>\
                        <a href="#">New Content 2</a></td></tr>');
}

这里的问题是在表中所有现有行之后添加了这一行,当我使用length属性检查a中的元素数量时,我总是得到2(我有最初2行)

alert('a.length') // this shows 2 

我想要的是直接父行而不是所有现有行,但我不知道为什么它不起作用?

编辑:SALESFORCE服务器提供的HTML代码:

<tbody id="j_id0:j_id3:j_id4:j_id6:tb">
<tr class="dataRow even first" onfocus="if (window.hiOn){hiOn(this);}" onblur="if (window.hiOff){hiOff(this);}" onmouseout="if (window.hiOff){hiOff(this);} " onmouseover="if (window.hiOn){hiOn(this);} ">
**<td id="j_id0:j_id3:j_id4:j_id6:0:ibrahim" class="dataCell " onclick="queryAndUpdateLead();" colspan="1">**
<td id="j_id0:j_id3:j_id4:j_id6:0:j_id7" class="dataCell " colspan="1">
<td id="j_id0:j_id3:j_id4:j_id6:0:j_id8" class="dataCell " colspan="1">
<td id="j_id0:j_id3:j_id4:j_id6:0:j_id9" class="dataCell " colspan="1">
<td id="j_id0:j_id3:j_id4:j_id6:0:j_id10" class="dataCell " colspan="1">
</tr>
<tr class="dataRow odd last" onfocus="if (window.hiOn){hiOn(this);}" onblur="if (window.hiOff){hiOff(this);}" onmouseout="if (window.hiOff){hiOff(this);} " onmouseover="if (window.hiOn){hiOn(this);} ">
<td id="j_id0:j_id3:j_id4:j_id6:1:ibrahim" class="dataCell " onclick="queryAndUpdateLead();" colspan="1">
<td id="j_id0:j_id3:j_id4:j_id6:1:j_id7" class="dataCell " colspan="1">
<td id="j_id0:j_id3:j_id4:j_id6:1:j_id8" class="dataCell " colspan="1">
<td id="j_id0:j_id3:j_id4:j_id6:1:j_id9" class="dataCell " colspan="1">
<td id="j_id0:j_id3:j_id4:j_id6:1:j_id10" class="dataCell " colspan="1">
</tr>
</tbody>
</table>

1 个答案:

答案 0 :(得分:0)

由于您收集了$('[id$=ibrahim]')个元素,因此您需要使用$(this)查找当前点击的元素中最接近的tr并在以下内容后插入该内容:

function queryAndUpdateLead() { 
        var $(this).closest('tr')
                .after('<tr><td>New Content 1</td><td>\
                        <a href="#">New Content 2</a></td></tr>');
}