2016-11-26 115 views
0

我想使用jQuery將特定表格單元格的#id變成變量,但沒有多少運氣。任何人都可以提供建議嗎?我做了一個小提琴here如何使用jQuery定位特定表格單元格?

HTML

<input type="button" id="button" value="Click Me" /> 

<table id="myTable1"> 
    <tbody> 
    <tr> 
     <td id="1"> 
     cell 1 
     </td> 
     <td id="2"> 
     Get the id of this cell 
     </td> 
     <td id="3"> 
     cell 2 
     </td> 
    </tr> 
    </tbody> 
</table> 

jQuery的

$(document).ready(function() { 
    $("#button").click(function() { 
    var td = $(this).closest('table').attr('id'); //find table id 
    alert(td); 
    }); 
}); 
+0

應該如何代碼知道哪個小區** **你想要的目標? –

+0

我希望你能幫助我。 – JulianJ

+0

使用'next'而不是''this(this).next('table')。attr('id');' – Azim

回答

1

這裏的第一個解決方案。如果你想獲得的所有的ID從每個細胞。希望能幫助到你!

$(document).ready(function() { 
 
$("#button").click(function() { 
 
    var ids = []; 
 
    $("tr > td").each(function(index){ 
 
    ids.push($(this).attr("id")); 
 
    }); 
 
    alert(ids); 
 
}); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<input type="button" id="button" value="Click Me" /> 
 

 
<table id="myTable1"> 
 
    <tbody> 
 
    <tr> 
 
     <td id="1"> 
 
     cell 1 
 
     </td> 
 
     <td id="2"> 
 
     Get the id of this cell 
 
     </td> 
 
     <td id="3"> 
 
     cell 2 
 
     </td> 
 
    </tr> 
 
    </tbody> 
 
</table>

這裏的第二個解決方案,如果你想看到的ID的一個接一個。

$(document).ready(function() { 
 
$("#button").click(function() { 
 
    $("tr > td").each(function(index){ 
 
    alert($(this).attr("id")); 
 
    }); 
 
}); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<input type="button" id="button" value="Click Me" /> 
 

 
<table id="myTable1"> 
 
    <tbody> 
 
    <tr> 
 
     <td id="1"> 
 
     cell 1 
 
     </td> 
 
     <td id="2"> 
 
     Get the id of this cell 
 
     </td> 
 
     <td id="3"> 
 
     cell 2 
 
     </td> 
 
    </tr> 
 
    </tbody> 
 
</table>

相關問題