[英]Retrieve The PHP variable Value of a HTMl Element Using Jquery inside a Loop
我有一個奇怪的問題。 我正在使用while循環使用PHP MySQL獲取表值,並將它們存儲在數組中。 然后,我在一個頁面中一個接一個地顯示它。
$sql = "select * from newsfeed order by id DESC";
$result = $db->query($sql);
$posts_array = array(); // Storing the result to an Custom Array
$index = 0;
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$posts_array[$index] = $row;
$index++;
}
}
我已經使用以下代碼成功將帖子的$ post_id設置到HTML元素上。
<?php
$array_size = sizeof($posts_array);
for($i = 0; $i < $array_size; $i++){
?>
<div class='wrapper' id='wrapper'>
<div class='user'>
<!-- Some Code -->
<?php
$post_id = $posts_array[$i][id];
?>
<input type='image' name='like' id='like' width='40' height='40' src='like_btn.png' value='<?php echo ($post_id);'?> />
<?php } ?>
現在,我想使用Jquery來獲取該值並進行一些數據庫工作。 我已經使用以下代碼訪問了該值:
<script type="text/javascript">
function justsomething() {
alert($(this).val());
}
</script>
問題是我只為每個帖子獲取最后一個帖子的id作為alert(),而不是獲取不同的id。 請幫我。 每次單擊並調用justsomething()函數時,PHP腳本是否正在加載,我感到困惑。
注意:我可以單獨顯示每個帖子的$ post_id,沒有任何問題。
因為id
對於一個html元素應該是唯一的,請嘗試將代碼更改為此:
<?php $array_size = sizeof($posts_array); for($i = 0; $i < $array_size; $i++){ ?>
<input type='image' name='like_<?php echo $i ?>' id='like_<?php echo $i ?>' width='40' height='40' src='like_btn.png' value='<?php echo $post_id;?>' onclick='justsomething(this);' />
<?php } ?>
<script>
function justsomething(el) {
var img = el;
alert(img.value);
}
</script>
這是一個例子
function justsomething(el) { var img = el; alert(img.value); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='image' name='like_1' id='like_1' width='40' height='40' src='like_btn.png' value='15454' onclick='justsomething(this);' />
它適用於循環,希望您可以使用它
$(“ input [id = like]”)。each(function(i){alert($(this).val());});
它將警告每個<input id="like"...
試試這個代碼:
onclick='justsomething(this)'
function justsomething(obj) {
alert($(obj).val());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.