0

我有一个非常简单的 jquery 问题,当我点击一个链接时,我需要在右边的 p (前面的表格行)中插入一些文本。

这是html:

<table>
<tr>
    <td>
        <p class='MyClass'>NOT HERE</p>
    </td>
</tr>
<tr>
    <td>
        <p class='MyClass'>NOT HERE</p>
    </td>
</tr>
.
. //Many table rows
.
<tr>
    <td>
        <p class='MyClass'>HERE I WANT TO INSERT THE TEXT</p>
    </td>
</tr>
<tr>
    <td>
        <div>
             <a href='#' class='MyLink'>insert text</a>
        </div>
    </td>
</tr>
</table>

这是jQuery:

$('.MyLink').click(function() {
    HOW CAN I MAKE SOME TEXT GO INTO THE RIGHT <p> HERE?
});
4

3 回答 3

1
$(this).closest('tr').prev('tr').find('.myClass').html('text here');

(未经测试)

于 2009-12-11T22:13:06.113 回答
0

一种真正简单的方法是给予:

<p class='MyClass'>HERE I WANT TO INSERT THE TEXT</p>

类或 ID,以便您可以直接引用它。例如:

<p id="insertHere" class='MyClass'>HERE I WANT TO INSERT THE TEXT</p>

然后你可以做类似的事情:

$('.MyLink').click(function() {
    $("#insertHere").text($("#insertHere").text() + "SOME TEXT YOU WANT TO INSERT");
});

如果您想以其他方式指定“插入”P,只需将选择器从“#insertHere”更改为定义要插入的 P 的选择器。

另外,我认为:

$('.MyLink').click(function() {
    $("#insertHere").append("SOME TEXT YOU WANT TO INSERT");
});

也会起作用(而且会更短),但我不是 100% 确定(所以先测试)。

于 2009-12-11T22:13:26.130 回答
0
$(this).parents('tr:first').prev('tr').find('.myClass').html("The Text that you want");

.parents walks up the dom to the first tr above your link, then prev('tr') takes you to the previous row, and finally the find searches down the tr for all elements that have the ".myClass" class.

于 2009-12-11T22:24:16.173 回答