如何在jQuery中选择下一个标签?

4
如何从我的位置选择具有class="date"和id="z"的标签?
<td style="width:300px;height:40px;" id="pricePanel">
    <div id="class">
        <label class="priceNumber" id="label">test</label>
        <div class="no" hidden="hidden">
            <input type="text" id='priceNumber' class="text" style="text-align:center;" onkeypress="if(event.keyCode==13)" value='@item.Cost.ToString()' />
        </div>
    <div>
</td>
<td id="x">
    <label class="date" id="z">@date</label>
</td>

我在jQuery代码中的文本框块中。

$(".text").live("keypress", function (event) {
        //Here I want to change the text of the label with class="date" and id="z"
    });

注意:在主代码中,我有一个循环,不幸的是有一些带有相同类和id的标签,因此我想选择在我更改其文本的文本框之后的标签。

在主代码中,我有一个循环,不幸的是有一些标签具有相同的类和ID,因此我想选择在我更改其文本的文本框之后的标签。 - Hamid Reza
4个回答

6

使用$(this)引用来获取当前位置... 使用parents('td')移动到<td>...使用next()获取下一个<td>,使用find获取标签。尝试一下吧。

 $("div.no").on("keypress",".text", function (event) {
   $(this).parents('td').next().find('#z').text();
});

然而,由于标签中有id属性...直接使用它作为选择器在性能上更好且更快。

 $(".text").on("keypress", function (event) {
   $('#z').text();  // $('label.date').text();
});

2
您可以使用closest()方法来访问文本的父级td,然后使用next()方法访问下一个td,并使用find()方法查找给定类别的标签。您可能有重复的结构,并且使用相同的id来禁止使用多个元素,因此请使用带有标签的class。如果没有重复的结构,则可以直接使用id演示 您还没有关闭第一个td中的第一个
标签。 Html
<table>
    <tr>
        <td style="width:300px;height:40px;" id="pricePanel">
            <div id="class">
                <label class="priceNumber" id="label">test</label>
                <div class="no">
                    <input type="text" id='priceNumber' class="text" style="text-align:center;"
                    onkeypress="if(event.keyCode==13)" value='@item.Cost.ToString()' />
                </div>
            </div>
        </td>
        <td id="x">
            <label class="date" id="z">@date</label>
        </td>
    </tr>
</table>

Javascript

$(".text").live("keypress", function (event) {
    $(this).closest('td').next('td').find('.date').text("your text");
});

如果您没有重复的块并且只有单个块,则直接使用id。
$(".text").live("keypress", function (event) {
    $('#z').text("your text");
});

Live已过时,如果可能,请使用on


当然,你的答案是正确的,但如果我能为两个答案都打对勾就更好了。非常感谢。;) - Hamid Reza

1
   $(".text").live("keypress", function (event) {
             $("label#z").text(/*your text*/)
        });

1

使用ID / class是识别对象的更快捷的方法

直接使用ID属性(假设“z”是唯一的id)

$('#z').text("your text")

如果 z 是重复的,则最好使用类。
$('label.date').text("your text")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接