2017-03-12 88 views
0

我從PHP生成的HTML表(從SQL查詢的結果):PHP生成表按鈕的onclick僅適用於第一

echo "<table border=\"5\"><tr><th>Codice</th><th>Titolo</th><th>Anno Creazione</th><th>Materiale</th><th>Altezza</th><th>Peso</th><th>Museo</th></tr>"; 
while($row = mysqli_fetch_assoc($results)) { 
     echo "<tr><td>".$row["Codice"]."</td><td>".$row["Titolo"]."</td><td>".$row["Anno_creazione"]."</td><td>".$row["Materiale"]."</td><td>".$row["Altezza"]."</td><td>".$row["Peso"]."</td><td>".$row["Museo"]."</td><td><button id=\"modifica\" type=\"button\">Modifica</button></td><td><button id=\"cancella\" type=\"button\">Cancella</button></td></tr>"; 
} 
echo "</table>"; 

然後,我有這個jQuery:

$("#cancella").click(function(){ 
    if(confirm("Vuoi davvero eliminare questi dati?")){ 
     var codice = <?php echo json_encode($cod); ?>; 
     var tipo = <?php echo json_encode($tipo_opera); ?>; 
     window.location.href = "delete.php?codice="+codice+"&tipo="+tipo; 
    } 
}); 

此點擊功能僅適用於第一行的「刪除」按鈕。爲什麼?

回答

2

ID是唯一的,因此只能被分配給一個element

使用class

<button class=\"cancella\" type=\"button\">Cancella</button> 

$(".cancella").click(function(){ 
// Do Something. 
}); 

備選:

<button type=\"button\" onclick=\"cancella()\">Cancella</button> 

function cancella(){} 
+0

使用一個類,然後在單擊事件中使用'this'元素 – Hammerbot

+0

如果我使用的類不起作用,並且Chrome控制檯不返回錯誤 –

+0

讓我檢查... –

0
<button id=\"cancella\" type=\"button\">Cancella</button> 

需求是一類不是ID

0

ID應該是唯一的,如果這是你的DOM結構重複,那麼你將面臨問題。使用類cancella的東西,然後定義一些數據屬性來標識特定的元素,如果你想。

所以你的代碼會...

在HTML中

echo "<tr><td>".$row["Codice"]."</td><td>".$row["Titolo"]."</td><td>".$row["Anno_creazione"]."</td><td>".$row["Materiale"]."</td><td>".$row["Altezza"]."</td><td>".$row["Peso"]."</td><td>".$row["Museo"]."</td><td><button id=\"modifica\" type=\"button\">Modifica</button></td><td><button data-myid=".$row['id']." class='cancella' type=\"button\">Cancella</button></td></tr>"; 

在JS

$(".cancella").click(function(){ 
    if(confirm("Vuoi davvero eliminare questi dati?")){ 
    var particular_element = $(this).attr('data-myid'); 
    } 
}); 

此外,如果你是動態添加 「更多」 的元素,那麼你應該使用$(document).on('click', '.cancella', function(){});代替$(".cancella").click(),希望它有幫助。

相關問題