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,因此我想在我更改了文本的文本框之后选择标签。

4

4 回答 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();
});
于 2013-03-12T05:18:14.003 回答
2

您可以使用closest()到达td文本的父级,然后使用next()到达下一个 td 和find()给定类的标签。您可能有重复的结构,并且id禁止使用一个以上的元素,因此请class与标签一起使用。如果您没有重复的结构,请立即使用 id 。

现场演示

您也没有关闭第一个 td 中的第一个 div 。

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");
});

Liveon如果可能,不推荐使用。

于 2013-03-12T05:18:06.700 回答
1
   $(".text").live("keypress", function (event) {
             $("label#z").text(/*your text*/)
        });
于 2013-03-12T05:18:54.573 回答
1

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

直接使用id属性(考虑到“z”是唯一的id)

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

如果 z 是重复的,那么最好使用 class

$('label.date').text("your text")
于 2013-03-12T05:20:10.680 回答