javascript - 如何使用 JQuery Fancybox2 将嵌套输入隐藏子项的值获取到自定义内容中

标签 javascript jquery fancybox-2

HTML:

<div id="adContainer">
  <a class="iframe"  onclick="viewAd('<?=123?>')">This goes to iframe
     <input class='photo-id' type='hidden' value=123>
     <input class='photo-photo' type='hidden' value='name.jpg'>
  </a>
</div> 
<div id="adContainer">
  <a class="iframe" onclick="viewAd('<?=456?>')" >This goes to iframe
    <input class='photo-id' type='hidden' value=456>
    <input class='photo-photo' type='hidden' value='name2.jpg'>
  </a>
</div>   

JQuery/JavaScript:

$(document).ready(function(){
  $("a.iframe").fancybox({
    'height' : '98%',
    'autoScale' : true,
    'transitionIn' : 'elastic',
    'transitionOut' : 'fade',
    'type' : 'iframe',
    'content' : '<div class="customHTML"><h1>'+$(this).children("input.photo-id").attr("value")+'</h1><p><img src="'+$(this).children("input.photo-name").val()+'" alt="'+$(this).children("input.photo-name").val()+'"/></div>'
  });         
});


function viewAd(id){
  alert(id);
  // return "<p>Test</p>";
}

我可以让它在单个实例中工作

$("a.iframe input.photo-id").val() //always return 123

,但是当我有多个代码副本时,会插入第一个副本。

我尝试了以下方法,结果作为评论:

$(this).children("input.photo-id").attr("value")  /// Undefined
$(this).children("input.photo-id").val()        /// Undefined
$(this).children("input.photo-id").valueOf()      /// [Object object]
$(this).children("photo-id").val()              /// Undefined

最佳答案

由于您有相同限定条件的多个实例,因此您需要使用 $.each() 迭代每个元素以获得正确的值。

$("a.iframe").each(function() {
  $(this).fancybox({
    'height' : '98%',
    'autoScale' : true,
    'transitionIn' : 'elastic',
    'transitionOut' : 'fade',
    'type' : 'iframe',
    'content' : '<div class="customHTML"><h1>'+$(this).children("input.photo-id").attr("value")+'</h1><p><img src="'+$(this).children("input.photo-name").val()+'" alt="'+$(this).children("input.photo-name").val()+'"/></div>'
  });
});

关于javascript - 如何使用 JQuery Fancybox2 将嵌套输入隐藏子项的值获取到自定义内容中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34598379/

相关文章:

javascript - 正则表达式不能正常工作 neos

javascript - 如果在小型设备上用错误文本替换 iframe

javascript - 在普通 View 和代码 View 之间切换时保持光标位置

javascript - 克隆后无法从选择框中选择选项

javascript - .checkboxradio ('refresh' )问题,无法与禁用的预加载字段一起使用

jquery - 在 Trello 中,如何显示卡号?

javascript - 如何将附加内容放入 fancybox iframe 中

css - 防止 fancybox 返回页面顶部

javascript - 从字符串中获取CSS属性

jquery - 没有花式框滚动条