开发者

jquery traversing problem, insert text

I have a quite easy jquery question that I can't get right, when clicking on a link I need to insert some text in the right p (the table row before).

This is the 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>
开发者_如何学Python             <a href='#' class='MyLink'>insert text</a>
        </div>
    </td>
</tr>
</table>

This is the jquery:

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


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

(untested)


One real easy way would be to give:

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

a class or ID, so that you could reference it directly. For instance:

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

Then you could just do something like:

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

If you want to specify the "insert into" P some other way, just change the selector from "#insertHere" to one that defines which P you want to insert in to.

Also, I think:

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

will work too (and be shorter), but I'm not 100% certain (so test first).


$(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜