am使用jquery和php显示图像,并带有包含文件名的隐藏字段输入。我想当每个图像被点击时,我会将隐藏字段的值放入一个文本框中。
这是我的样例代码检索的jquery
$(document).ready(function() {
$.ajax({
type: "GET",
url: "getimages.php",
dataType: "html",
success: function(response){
$("#refresh").append(response);
}
});
});
检索图像的php代码
$query=$db->query("SELECT * FROM files");
while($val = $re->fetch(PDO::FETCH_ASSOC))
{
$name = $val['file_name'];
echo '<div class="image">
<input type="hidden" name="link" id="getname" value="'.$name.'" />
<img id="img" src="http://localhost/web/images/'.$val['file_name'].'" /></a>
</div>';
};
用于在点击每个图像时将隐藏字段值添加到文本框的代码
$(document).ready(function(){
$("#img").each(function(index){
$(this).click(function(){
var post=$(this).parent().parent().find('#getname').val();
var tbox = document.getElementById('txtbox');
tbox.value = post;
});
});
});
和文本框
<input type="text" id="txtbox" />
问题是,当我点击每个图像时,文本框不会被填充。
我该怎么办?
注意**使用jquery检索的图像和隐藏输入,如我的问题中所示
提前感谢
在php代码中,当while循环给出多个结果时,您将在while
循环中返回id,该循环将与您的id重复。
您通过$.ajax
调用获取图像,因此应该将clickhandler的附加移到success
回调中。你可以这样做,例如:
您可以从返回的html中删除id:
$query=$db->query("SELECT * FROM files");
while($val = $re->fetch(PDO::FETCH_ASSOC))
{
$name = $val['file_name'];
echo '<div class="image">
<input type="hidden" name="link" value="'.$name.'" />
<img width="100" src="images/'.$name.'" /></a>
</div>';
};
您可以将查找图像的方式更新为$(".image img")
,并使用.prev
:查找隐藏的input
字段
$(document).ready(function () {
var tbox = document.getElementById('txtbox');
$.ajax({
type: "GET",
url: "getimages.php",
dataType: "html",
success: function (response) {
$("#refresh").append(response);
$(".image img").each(function () {
$(this).click(function () {
tbox.value = $(this).prev('input').val();
});
});
}
});
});