2013-03-30 51 views
0

我有一個PHP while循環,我正在動態生成#id。在jquery腳本的頁面加載時獲取ID

例子:

<?php 
$i=1; 
while ($row = mysqli_fetch_array($result)): 
?> 

<tr> 
<td class='hashtag' id='status<?php echo $i; ?>'>status value</td> 
</tr> 

<?php 
$i++; 
endwhile: 
?> 

狀態ID都產生這樣的:狀態1,狀態2,STATUS3等等

我想在我的JS代碼在加載所有這些標識的用於顯示入模態對話框。

例子:

<script type="text/javascript"> 

$(document).ready(function(){ 

$("#status1"); 
$("#status2"); 
$("#status3"); 
. 
. 
and so on as per the php while loop. 

}); 
</script> 

我怎樣才能做到這一點?

+1

爲什麼不使用'$你叫他們在模板(」#標籤。 ').each()'函數? – arulmr

+2

mysqli? PDO ftw! – elclanrs

回答

3

您可以使用「Starts With」選擇:

$('td[id^="status"]').each(function(index){ 
    alert($(this).attr("id")); 
}); 

您可以以目標指定選擇的範圍主要TD的

+0

但是,我怎麼會得到status1,status2 ....等等使用這個? – Sky

+0

$('td [id^=「status」]')這將選擇所有td的ID以「status ****」開頭。您可以使用jquery的$ .each()來處理每個td.Its更好在這種情況下使用類而不是ID作爲選擇器 – Arvind

1

我會做這樣的:

更改您的HTML

<td class='hashtag status'>status value</td> 

然後js看起來像這樣:

$('.status').each(function(i, el){ 
    // the i value previously generated in php is here i += 1 if you need it 
    i += 1; 

    // here is your element. do whatever you want with it: 
    $(el).text('I am cell ' + i); 
}); 
+0

不,但只想要ID的那裏 – Sky

+0

爲什麼你只希望在那裏的ID?類有什麼問題?對我來說,用id來做這件事會感覺不對。那是什麼課程。 – stefreak

1
$("td[id^='status']").each(function(el){ 
    console.log(this.id); 
}); 

這會給你的每個元素的ID。

如果你只是想申請事件或插件,您可以通過做到這一點 -

$("td[id^='status']").pluginName(); 

$("td[id^='status']").on("click",function(){ 

}); 
相關問題