【问题标题】:Passing Data Attributes from Anchor Element to jQuery Function将数据属性从锚元素传递给 jQuery 函数
【发布时间】:2013-12-16 13:33:54
【问题描述】:

我有一个需要在弹出窗口中打开的共享图标和网址列表,即:facebook、twitter 等。

我有一个不记得在哪里找到的 jQuery popupWindow 函数,但它采用以下设置列表:

$.fn.popupWindow.defaultSettings = {
    centerBrowser:0,
    centerScreen:0,
    height:500,
    left:0,
    location:0,
    menubar:0,
    resizable:0,
    scrollbars:0,
    status:0,
    width:500,
    windowName:null,
    windowURL:null,
    top:0,
    toolbar:0
};

所以我可以简单地传递高度、宽度和中心来获得一个非常好的共享弹出窗口,如下所示:

$(element).popupWindow({ 
    centerBrowser: 1,
    width: 500,
    height: 250 
});

我遇到的问题是我无法访问链接的数据属性,以便将高度和宽度传递给 popover 方法。

我的链接类似于:

<a href="http://www.facebook.com/sharer.php?etc" 
    class="social-share facebook" 
    data-width="550" 
    data-height="275">Share on Facebook</a>

试过了:

$('.social-share').popupWindow({ 
    centerBrowser: 1,
    height: $(this).attr('data-height'),
    width: $(this).attr('data-width')
});

这只是忽略脚本并在同一窗口中转到 FB。

试过了:

$('.social-share').popupWindow({ 
    centerBrowser: 1,
    height: this.attr('data-height'),
    width: this.attr('data-width')
});

对象没有属性attr。

在 popupWindow 函数中,他们编写了一些覆盖,首先选择元素的属性,然后回退到如下设置:

settings.windowName = this.name || settings.windowName;
settings.windowURL = this.href || settings.windowURL;

我的想法是这是最优雅和功能最强大的解决方案,这样会有一个三重回退,先看看有没有data-widthdata-height属性,然后检查传入的设置,然后使用默认设置.

但是,唉,我似乎也无法让它发挥作用。

我尝试添加两者:

settings.width = $(this).attr('data-width') || settings.width;
settings.height = $(this).attr('data-height') || settings.height;

这对高度或宽度没有影响,只是使用默认值。

并尝试过:

settings.width = this.attr('data-width') || settings.width;
settings.height = this.attr('data-height') || settings.height;

这会抛出错误对象没有属性attr。

帮助!

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    试试这个 与其频繁访问 DOM,不如尝试使用 .data() 我想问题是您缺少添加 units

    $('.social-share').popupWindow({ 
        centerBrowser: 1,
        height: this.data('height') + 'px',
        width:  this.data('width') + 'px'
    });
    

    【讨论】:

    • 对象没有属性数据。另外,popupWindow 函数在设置中不采用单位。
    猜你喜欢
    • 2011-07-15
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2022-07-28
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    相关资源
    最近更新 更多