douyuan4357 2016-02-08 14:06
浏览 37
已采纳

来自php foreach循环的隐藏输入值未正确传递给JQuery

HTML + PHP :

<?php foreach ($resultpics as $row1){ ?>
<div class="col-md-2">
<a href="#" class="thumbnail" data-popup-open="popup-1"<!-onclick="showImg(<?php //echo $row1['img_id']; ?>-->)">
<input type="hidden" name="imgid" value="<?php echo $row1['img_id']; ?>" id="imgid">
<img id="popimg" src="<?php echo $row1['img_path'];?>/<?php echo $row1['img_id']; ?>.jpg" alt="Pulpit Rock" style="width:200px;height:150px;">  
</a>
</div>  
<?php } ?>

JQuery:

$('[data-popup-open]').on('click', function(e)  {
    var targeted_popup_class = jQuery(this).attr('data-popup-open');
    $('[data-popup="' + targeted_popup_class + '"]').fadeIn(350);
    var imgid = $('input[name=imgid]').val();
    alert(imgid);
    $('img#viewimg').attr('src','images/'+imgid+'.jpg');
    e.preventDefault();
});

The problem is the value of

var imgid
is always same(on every different it gives the imgid of first image only). Note that there is no problem in php foreach loop, it fetch's correctly. Thanks
  • 写回答

4条回答 默认 最新

  • dtpw54085 2016-02-08 14:43
    关注

    the problem is you have multiple input elements having name="imgid". So when you query $('input[name=imgid]') jquery parses all of the DOM and creates an object having 0 to 'n' input tags (n being the number of elements matching your query). If you use val() on this object it will always return the value of 0'th element in the object.

    Solution:

    change this

    var imgid = $('input[name=imgid]').val(); 
    

    to this

    var imgid = $(this).next().val(); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据