我正在尝试将锚标记的ID传递给jquery,但它无法正常工作

时间:2016-05-06 19:08:17

标签: javascript jquery html fancybox

我正在使用精美的盒子,我正在尝试用弹出的图像打开一个链接。

我的html打开了fancybox图片

<div id="isotope">
        <a href="img/portfolio/digitallifeWebsite.png" class="item branding webdesign" data-fancy="gal" id="http://www.digitallife.space/"><img src="img/portfolio/digitallifeWebsite.png" alt="digital life website"></a>
        <a href="img/portfolio/redandwhite.png" class="item branding webdesign" data-fancy="gal" id="http://www.redandwhiteinsight.com/"><img src="img/portfolio/redandwhite.png" alt="Red and white insight"></a>
</div>

单击图像时激活fancybox的jquery

lightBox: function() {
  $('#isotope a').fancybox({
    onComplete: function () {
        $("#fancybox-img").wrap($("<a />", {
            // set anchor attributes
            href: this.id, // THIS DOESN'T WORK
            target: "_blank" 
        }));
    }
});
},

这是我现在获得的一些代码的一部分我正在为自己修改它。不确定&#34; lightBox&#34;是

当我将href更改为

href: this.href,

或者

href: 'http://www.google.com/'

它有效

但是

href: this.id,

不起作用!如何让它使用id作为href的东西?

我的console.log($ this)

http://imgur.com/GIPJiLB

5 个答案:

答案 0 :(得分:0)

您是否尝试过$(this).attr('id');

无论如何,我认为最好更改数据ID 中的 ID 属性并使用$(this).attr('data-id');

答案 1 :(得分:0)

有多个锚标记,因此您可能需要包装每个锚标记

答案 2 :(得分:0)

不是在id属性中给出你的值,而是在anchor标签的rel属性中给它,然后检查$(this).attr(&#39; rel&#39;);

答案 3 :(得分:0)

问题发生是因为 php artisan serve --host=www.test.io --port=8001 有另一个上下文,而不是锚。

this(图片上)事件的处理程序在哪里?你提供的任务信息非常少。

无论如何,要实现你想要的东西,你可以这样做(这只是一个简单的例子,我不知道你的代码是什么样的):

click

并传递“href”(如果需要,你可以让他成为全局变量)

$('img').on('click', function() {
  // "this" equal to the element on which you clicked
  var href = $(this).closest('a') // find anchor
                    .attr('id'); // get attribute id
});

答案 4 :(得分:0)

所以我用这段代码解决了这个问题。

$(document).ready(function () {

    $('#isotope a').each(function(i) {
        var id = $(this).attr('id');
        $(this).fancybox({
            onComplete: function () {

                $("#fancybox-img").wrap($("<a />", {
                    // set anchor attributes
                    href: id, //or your target link
                    target: "_blank"
                }));
            }
        });
        });

});
相关问题