2013-03-12 30 views
2

如何從我的位置選擇class =「date」和id =「z」的標籤?如何選擇jQuery中的下一個標籤?

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

注:在主代碼中,我有一個循環,不幸的是有一些標籤具有相同class和id正因爲如此,我想在改變文本的文本框之後選擇標籤。

+0

在主代碼中,我有一個循環,不幸的是,有一些標籤具有相同的類和標識,因此我希望在更改文本的文本框之後選擇標籤。 – 2013-03-12 05:23:29

回答

4

使用$(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。

Live Demo

你是不是在第一個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"); 
}); 

Live不贊成使用on如果可能的話。

+0

你的回答是真實的,但如果我可以打2個答案的coorect答案的標誌。謝謝很多;) – 2013-03-12 05:35:23

+0

不客氣..... – Adil 2013-03-12 05:35:56

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

使用ID /類是更快的方法來識別和對象

直接使用ID屬性(考慮到 「Z」 是一個唯一的ID)

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

如果z是重複的然後更好地使用類

$('label.date').text("your text")