使用jQuery更新Pinterest Profile Widget中的链接

时间:2015-02-28 22:53:08

标签: jquery href pinterest

我一直在尝试使用jQuery来更新生成的Pinterest Profile Widget中的链接。该代码是通过Pinterest为我的客户网站生成的。

这是嵌入的代码:

<a data-pin-do="embedUser" href="http://www.pinterest.com/aliceandlois/" data-pin-scale-width="155" data-pin-scale-height="130" data-pin-board-width="985"></a>

然后生成的代码如下:

<a class="PIN_1425163222617_embed_grid_th" title="Pom Pom Wall Hanging &mdash; Simple to make and so cute!" data-pin-href="//www.pinterest.com/pin/452963674997848977/repin/x/" data-pin-id="452963674997848977" data-pin-log="embed_user_thumb" style="height: 130px; width: 155px; top: 0px; left: 0px;"><img src="http://media-cache-ak0.pinimg.com/237x/cd/4d/74/cd4d749b360486b0fd4706f1a068c5ce.jpg" data-pin-nopin="true" class="PIN_1425163222617_embed_grid_img" alt="Pom Pom Wall Hanging &amp;#8212; Simple to make and so cute!" style="height: 232.173px; width: 155px; min-height: 232.173px; min-width: 155px; margin-top: -116.086px;"></a>

我要做的是更新“data-pin-href”中的URL以删除URL的“repin / x /”部分,以便它可以读取,例如//www.pinterest.com/ pin / 452963674997848977 /而不是//www.pinterest.com/pin/452963674997848977/repin/x /

这需要为窗口小部件中的每个图像自动完成(有20个)。

我尝试使用How to change the href for a hyperlink using jQuery上发布的教程来完成此操作,但是,我无法使用data-pin-href属性而不是标准href。

我也发现这个jSFiddle我认为可以帮助我,所以我修改了代码作为nessesary,但仍然没有快乐:http://jsfiddle.net/TexasBrawler/uQd9h/1/

任何人都可以为我提供有效的解决方案吗?

由于

编辑:一直在进一步研究如何解决这个问题,但仍然没有快乐。我在尝试解决方案时引用了以下链接:

How to set data attributes in HTML elements

JQuery updating data- attribute

Updating the value of data attribute using jQuery

1 个答案:

答案 0 :(得分:0)

经过多次尝试后,我自己设法解决了这个问题。

我尝试的最终代码的初始版本是:

$('.pinterest-block a[data-pin-href]').each(function(){
    var newurl = $(this).attr('data-pin-href').replace('repin/x/','');
    $(this).attr('data-pin-href', newurl);
});

虽然这在我对jSFiddle的测试中起作用,但我很困惑它在尝试使用实时代码时无法正常工作。

我确定问题与您在代码中嵌入的Pinterest脚本文件有些不同:<script type="text/javascript" src="//assets.pinterest.com/js/pinit.js"></script>

当文档准备好并替换时,他们的脚本会运行:

<a data-pin-do="embedUser" href="http://www.pinterest.com/aliceandlois/" data-pin-scale-width="155" data-pin-scale-height="130" data-pin-board-width="985"></a>

....输出数据。

我的代码也在文档就绪上运行,所以实际上它正在尝试更新那些甚至还没有的东西(我认为....)。

因此,我通过稍微延迟执行代码解决了这个问题:

window.setTimeout(function (){
        $('.pinterest-block a[data-pin-href]').each(function(){
            var newurl = $(this).attr('data-pin-href').replace('repin/x/','');
            $(this).attr('data-pin-href', newurl);
        });
    }, 1500);

这解决了这个问题,因为data-pin-href现在可以根据需要更新。

如果有人对我的解决方案有更精简的版本,请随时发布,但是,我不相信它可以进一步浓缩。

JSFiddle:http://jsfiddle.net/fBW4V/14/