簡體   English   中英

jQuery $ .parents()無法正常運行

[英]jQuery $.parents() not Functioning Properly

我的html文件中有以下代碼,我想訪問元素的祖父母,例如表,它是以下代碼中td的祖父母。 為此,我使用了以下jQuery語法,但顯示為“未定義”。 誰能指導我問題出在哪里?

  <script type="text/javascript">

   $(document).ready(function () {
     alert($('td[id="4"]').parents().eq(1).attr("id"));
  });

</script> 

<title></title>
</head>
<body>
<form id="form1" runat="server">
  <div  class="ui-layout-center" id="center" runat="server">
     <table id="Table1" >             
        <tr id="tr1">
            <td id="3" class="cell" >
               first cell 
            </td>
            <td id="4" class="cell">
            second cell
            </td>
        </tr> 
     </table>
    <br />
    <br />
  </div>
</form>
</body>
</html>

首先,在加載DOM之前,您無法運行代碼。 這意味着您必須將其放在相關HTML之后的源文件中,或者使用jQuery的方法來等待DOM加載:

$(document).ready(function() {
    alert($('td[id="4"]').parents().eq(0).attr("id"));
});

然后,您的代碼:

$('td[id="4"]').parents().eq(0)

正在獲取匹配的td元素的第一個父對象。 該第一個父對象將是tr標簽,該標簽將提醒它的ID,而不是<table>元素的ID,如您在此處看到的: http : //jsfiddle.net/jfriend00/rxUEp/

如果需要表元素的ID,則最好使用以下代碼指定所需的實際父項:

$(document).ready(function() {
    alert($('td[id="4"]').closest("table").attr("id"));
});

為了進一步解決問題,ID值應以下划線或字母開頭,而不是數字,並且一旦有了有效的ID,就應該使用效率更高的選擇器,如下所示:

<table id="Table1" >
    <tr id="tr1">
        <td id="cell3" class="cell" >
           first cell 
        </td>
        <td id="cell4" class="cell">
        second cell
        </td>
    </tr> 
</table>

$(document).ready(function() {
    alert($('#cell4').closest("table").attr("id"));
});

PS使用.closest("table")來查找所需父項的另一個原因是,表都具有隱式的<tbody>標記(即使它不在HTML中),這意味着實際的<table>標記實際上是從您的<td>到第三個父級。 使用.closest("table") ,您不必擔心這些查找詳細信息,因為jQuery只是查找您指定的詳細信息。

您正在尚不存在的表上運行代碼。 <script>塊移動到表下方,即可工作(盡管您將獲取tr父級,而不是table父級),或將其放在onready函數中,以便直到整個DOM完成后才觸發。

演示:(提示兩次,在表前一個,后一個) http://jsfiddle.net/Fzcv4/1/

如果您明確知道要使用哪個父元素,請嘗試使用最近的:

$(function() {
    alert($('td[id="4"]').closest("table").attr("id"));
});

同樣,以數字開頭的id屬性無效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM