[英]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.