2 回答

TA貢獻1816條經驗 獲得超6個贊
最好將腳本移出循環,一次性獲取所有按鈕,然后綁定單擊事件:
// Create all buttons, with class "text-button"
<?php for($i=0;$i<5;$i++): ?>
<button class="text-button" id="text<?php echo $i; ?>">hello </button>
<?php endif; ?>
<script>
// On document ready
$(document).ready(function() {
// Find all buttons with class "text-button"
$(".text-button").click(function(e) {
alert("hello");
// Log the clicked button
console.log(e.currentTarget);
console.log(e.currentTarget.id);
})
})
</script>

TA貢獻1943條經驗 獲得超7個贊
并且刪除$(doucment).ready()將解決您的問題。像這樣。
<?php
for($i=0;$i<5;$i++){
?>
<button id="text<?php echo $i; ?>">hello </button>
<script>
var i=<?php echo $i; ?>;
$("#text"+i).click(function(){
alert("hello");
});
</script>
<?php } ?>
- 2 回答
- 0 關注
- 137 瀏覽
添加回答
舉報