Fancybox:获取点击的锚点/元素的ID

我想在fancybox中获取clicked / shown元素的id。 我已经尝试了“this.id”和“this.attr(”id“)” – 但它们都不起作用。

$("a.lightbox_image").fancybox({ 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'speedIn': 600, 'speedOut': 200, 'content': 'Id of element clicked'+this.attr("id") }); 

有什么建议?

你可以这样做:

 $("a.lightbox_image").each(function() { $(this).fancybox({ 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'speedIn': 600, 'speedOut': 200, 'content': 'Id of element clicked' + this.id }); }); 

this可能指向您当前绑定的window (或者如果在ready事件中document ,则无法查看更多代码)。 要.each()成为你想要的 ,你应该使用.each()循环并在那里分配…在.each()闭包内, this指的是锚。

我在使用Nick Craver的解决方案和“onClosed”function时遇到了问题,经过一些测试我找到了可行的解决方案:

 $("a.lightbox_image").each(function() { var tthis = this; $(this).fancybox({ 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'speedIn': 600, 'speedOut': 200, onClosed : function() { alert(this.id); } }); }); 

在我的情况下,这用于在关闭编辑数据的fancybox窗口后重新加载数据行。

这似乎对我有用:)

  

javascript:

  $(document).ready(function() { $(".fancybox").attr('rel', 'gallery').fancybox({ loop : false, afterLoad: function(current, previous) { console.log(this.element[0].id) console.info( 'Current: ' + current.href ); console.info( 'Previous: ' + (previous ? previous.href : '-') ); if (previous) { console.info( 'Navigating: ' + (current.index > previous.index ? 'right' : 'left') ); //When navigating, we want to add the next set of images! :) new_images = getNextFancyImages(current.index > previous.index ? 'right' : 'left') } } }); }); 

在firebug中,你可以看到日志:)

建议使用每个循环的答案是正确的,但如果您使用任何回调(beforeShow,beforeLoad,onUpdate等),那么需要了解一个重要细节。

在每个循环的上下文中, 指的是将被单击的元素。 但是只要你进入fancybox回调,就会引用fancybox对象。 诀窍是将元素存储到另一个变量中,例如。 然后在回调中参考。

 $('.fancybox').each(function() { var that = this; $(this).fancybox({ beforeLoad: function() { var id = $(that).attr('id'); console.log("id of element clicked is: "+id) } }); }); 

each(function()解决方案都会破坏图库(换句话说,不再有Next和Prev按钮)。

似乎可以工作并保存库的解决方案是在调用fancyBox之前为元素上的click事件分配一个函数,并将id保存到唯一的div。

例如:

 $(document).ready(function() { $(".fancybox").click(function() { $("#").data("clickedid", this.id); }).fancybox({ beforeShow: function () { this.title += '
'; this.title += 'Clicked id: ' + $("#
").data("clickedid"); }, prevEffect: 'none', nextEffect: 'none', loop: false, fitToView: false, helpers: { title: { type: 'inside' } } }); });