javascript 如何重新渲染 Pinterest 的 Pin It 按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9352021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:21:54  来源:igfitidea点击:

How can i rerender Pinterest's Pin It button?

javascriptajaxasynchronouspinterest

提问by onur

I'm trying to create and manipulate the Pin It button after page load. When i change the button properties with js, it should be rerendered to get the functionality of pinning dynamically loaded images. So, does Pinterest have any method like Facebook's B.XFBML.parse() function?

我正在尝试在页面加载后创建和操作 Pin It 按钮。当我使用 js 更改按钮属性时,应该重新渲染它以获得固定动态加载图像的功能。那么,Pinterest 有没有像 Facebook 的 B.XFBML.parse() 函数那样的方法?

Thanks...

谢谢...

回答by Styx

Just add data-pin-buildattribute to the SCRIPTtag:

只需data-pin-buildSCRIPT标签添加属性:

<script defer
  src="//assets.pinterest.com/js/pinit.js"
  data-pin-build="parsePinBtns"></script>

That causes pinit.jsto expose its internal buildfunction to the global windowobject as parsePinBtnsfunction.

这导致pinit.js将其内部build函数window作为parsePinBtns函数公开给全局对象。

Then, you can use it to parse links in the implicit element or all of the links on the page:

然后,您可以使用它来解析隐式元素中的链接或页面上的所有链接:

// parse the whole page
window.parsePinBtns();

// parse links in #pin-it-buttons element only
window.parsePinBtns(document.getElementById('pin-it-buttons'));

Hint:to show zero count just add data-pin-zero="1"to SCRIPTtag.

提示:要显示零计数,只需添加data-pin-zero="1"SCRIPT标签。

回答by Carlo Mallone

The best way to do this:

最好的方法是:

  1. Remove the iframe of the Pin It button you want to manipulate
  2. Append the html for the new button manipulating it as you wish
  3. Realod their script - i.e. using jQuery:

    $.ajax({ url: 'http://assets.pinterest.com/js/pinit.js', dataType: 'script', cache:true});
    
  1. 删除您要操作的 Pin It 按钮的 iframe
  2. 附加新按钮的 html,按您的意愿操作它
  3. 重新编写他们的脚本 - 即使用 jQuery:

    $.ajax({ url: 'http://assets.pinterest.com/js/pinit.js', dataType: 'script', cache:true});
    

回答by Tsanyo Tsanev

To render a pin-it button after a page has loaded you can use:

要在页面加载后呈现 pin-it 按钮,您可以使用:

<a href="..pin it link.." id="mybutton" class="pin-it-button" count-layout="none">
    <img border="0" src="//assets.pinterest.com/images/PinExt.png" width="43" height="21" title="Pin It" />
</a>
<script>
    var element = document.getElementById('mybutton');
    (function(x){ for (var n in x) if (n.indexOf('PIN_')==0) return x[n]; return null; })(window).f.render.buttonPin(element);
</script>

Assuming of course the assets.pinterest.com/js/pinit.jsis already loaded on the page. The render object has some other useful methods like buttonBookmark, buttonFollow, ebmedBoard, embedPin, embedUser.

当然,假设assets.pinterest.com/js/pinit.js已经加载到页面上。渲染对象还有一些其他有用的方法,如buttonBookmarkbuttonFollowebmedBoardembedPinembedUser

回答by Jay Paroline

I built on Derrek's solution (and fixed undeclared variable issue) to make it possible to dynamically load the pinterest button, so it can't possibly slow down load times. Only tangentially related to the original question but I thought I'd share anyway.

我以 Derrek 的解决方案(并修复了未声明的变量问题)为基础,使动态加载 pinterest 按钮成为可能,因此它不可能减慢加载时间。仅与原始问题相关,但我想无论如何我都会分享。

at end of document:

在文件末尾:

<script type="text/javascript">
addPinterestButton = function (url, media, description) {
    var js, href, html, pinJs;
    pinJs = '//assets.pinterest.com/js/pinit.js';
    //url = escape(url);
    url = encodeURIComponent(url);
    media = encodeURIComponent(media);
    description = encodeURIComponent(description);
    href = 'http://pinterest.com/pin/create/button/?url=' + url + '&media=' + media + '&description=' + description;
    html = '<a href="' + href + '" class="pin-it-button" count-layout="vertical"><img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" /></a>';
    $('#pinterestOption').html(html);

    //add pinterest js
    js = document.createElement('script');
    js.src = pinJs;
    js.type = 'text/javascript';
    document.body.appendChild(js);
}
</script>

in document ready function:

在文档准备功能中:

addPinterestButton('pageURL', 'img', 'description');//replace with actual data

in your document where you want the pinterest button to appear, just add an element with the id pinterestOption, i.e.

在您希望 pinterest 按钮出现的文档中,只需添加一个带有 id pinterestOption 的元素,即

<div id="pinterestOption"></div>

hope that helps someone!

希望对某人有所帮助!

回答by Mike Kibbel

I rewrote the Pinterest button code to support the parsing of Pinterest tags after loading AJAX content, similar to FB.XFBML.parse() or gapi.plusone.go(). As a bonus, an alternate JavaScript file in the project supports an HTML5-valid syntax.

我重写了 Pinterest 按钮代码,支持加载 AJAX 内容后解析 Pinterest 标签,类似于 FB.XFBML.parse() 或 gapi.plusone.go()。作为奖励,项目中的备用 JavaScript 文件支持 HTML5 有效语法。

Check out the PinterestPlus project at GitHub.

在 GitHub 上查看PinterestPlus 项目。

回答by Cheeso

Here's what I did.

这就是我所做的。

First I looked at pinit.js, and determined that it replaces specially-marked anchor tags with IFRAMEs. I figured that I could write javascript logic to get the hostname used by the src attribute on the generated iframes.

首先,我查看了 pinit.js,并确定它用 IFRAME 替换了特殊标记的锚标记。我想我可以编写 javascript 逻辑来获取生成的 iframe 上的 src 属性使用的主机名。

So, I inserted markup according to the normal recommendations by pinterest, but I put the anchor tag into an invisible div.

所以,我根据 pinterest 的正常建议插入了标记,但我将锚标签放入了一个不可见的 div 中。

<div id='dummy' style='display:none;'>
<a href="http://pinterest.com/pin/create/button/?
    url=http%3A%2F%2Fpage%2Furl
    &media=http%3A%2F%2Fimage%2Furl" 
   class="pin-it-button" count-layout="horizontal"></a>
</div>
<script type="text/javascript" src="//assets.pinterest.com/js/pinit.js">
</script>

Then, immediately after that, I inserted a script to slurp up the hostname for the pinterest CDN, from the injected iframe.

然后,紧接着,我插入了一个脚本,从注入的 iframe 中提取 pinterest CDN 的主机名。

//
// pint-reverse.js
//
// logic to reverse-engineer pinterest buttons.
//
// The standard javascript module from pinterest replaces links to
// http://pinterest.com/create/button with links to some odd-looking
// url based at cloudfront.net. It also normalizes the URLs.
//
// Not sure why they went through all the trouble. It does not work for
// a dynamic page where new links get inserted.  The pint.js code
// assumes a static page, and is designed to run "once" at page creation
// time.
//
// This module spelunks the changes made by that script and
// attempts to replicate it for dynamically-generated buttons.
//

pinterestOptions = {};

(function(obj){

    function spelunkPinterestIframe() {
        var iframes = document.getElementsByTagName('iframe'),
            k = [], iframe, i, L1 = iframes.length, src, split, L2;

        for (i=0; i<L1; i++) {
            k.push(iframes[i]);
        }
        do {
            iframe = k.pop();
            src = iframe.attributes.getNamedItem('src');
            if (src !== null) {
                split = src.value.split('/');
                L2 = split.length;
                obj.host = split[L2 - 2];
                obj.script = split[L2 - 1].split('?')[0];
                //iframe.parentNode.removeChild(iframe);
            }
        } while (k.length>0);
    }

    spelunkPinterestIframe();

}(pinterestOptions));

Then,

然后,

function getPinMarkup(photoName, description) {
    var loc = document.location,
        pathParts = loc.pathname.split('/'),
        pageUri = loc.protocol + '//' + loc.hostname + loc.pathname,
        href = '/' + pathToImages + photoName,
        basePath = (pathParts.length == 3)?'/'+pathParts[1]:'',
        mediaUri = loc.protocol+'//'+loc.hostname+basePath+href,
        pinMarkup;

    description = description || null;

    pinMarkup = '<iframe class="pin-it-button" ' + 'scrolling="no" ' +
        'src="//' + pinterestOptions.host + '/' + pinterestOptions.script +
        '?url=' + encodeURIComponent(pageUri) +
        '&media=' + encodeURIComponent(mediaUri);

    if (description === null) {
        description = 'Insert standard description here';
    }
    else {
        description = 'My site - ' + description;
    }

    pinMarkup += '&description=' + encodeURIComponent(description);
    pinMarkup += '&title=' + encodeURIComponent("Pin this " + tagType);
    pinMarkup += '&layout=horizontal&count=1">';
    pinMarkup += '</iframe>';
    return pinMarkup;
}

And then use it from jQuery like this:

然后像这样从 jQuery 使用它:

    var pinMarkup = getPinMarkup("snap1.jpg", "Something clever here");
    $('#pagePin').empty(); // a div...
    $('#pagePin').append(pinMarkup);

回答by Derrick Grigg

Try reading this post http://dgrigg.com/blog/2012/04/04/dynamic-pinterest-button/it uses a little javascript to replace the pinterest iframe with a new button and then reloads the pinit.js file. Below is the javascript to do the trick

尝试阅读这篇文章http://dgrigg.com/blog/2012/04/04/dynamic-pinterest-button/它使用一个小 javascript 用一个新按钮替换 pinterest iframe,然后重新加载 pinit.js 文件。下面是做这个伎俩的javascript

refreshPinterestButton = function (url, media, description) {
    var js, href, html, pinJs;
    url = escape(url);
    media = escape(media);
    description = escape(description);
    href = 'http://pinterest.com/pin/create/button/?url=' + url + '&media=' + media + '&description=' + description;
    html = '<a href="' + href + '" class="pin-it-button" count-layout="horizontal"><img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" /></a>';
    $('div.pin-it').html(html);

    //remove and add pinterest js
    pinJs = $('script[src*="assets.pinterest.com/js/pinit.js"]');
    pinJs.remove();
    js = document.createElement('script');
    js.src = pinJs.attr('src');
    js.type = 'text/javascript';
    document.body.appendChild(js);
}

回答by Sreejith Sreenivasan

Here is what i did.. A slight modification on @Derrick Grigg to make it work on multiple pinterest buttons on the page after an AJAX reload.

这就是我所做的.. 对@Derrick Grigg 稍作修改,使其在 AJAX 重新加载后在页面上的多个 pinterest 按钮上工作。

refreshPinterestButton = function () {
    var url, media, description, pinJs, href, html, newJS, js;
    var pin_url;
    var pin_buttons = $('div.pin-it a');
    pin_buttons.each(function( index ) {
        pin_url = index.attr('href');
        url = escape(getUrlVars(pin_URL)["url"]);
        media = escape(getUrlVars(pin_URL)["media"]);
        description = escape(getUrlVars(pin_URL)["description"]);
        href = 'http://pinterest.com/pin/create/button/?url=' + url + '&media=' + media + '&description=' + description;
        html = '<a href="' + href + '" class="pin-it-button" count-layout="horizontal"><img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" /></a>';
        index.parent().html(html);
    });

    //remove and add pinterest js
    pinJs = '//assets.pinterest.com/js/pinit.js';
    js = $('script[src*="assets.pinterest.com/js/pinit.js"]');
    js.remove();
    js = document.createElement('script');
    js.src = pinJs;
    js.type = 'text/javascript';
    document.body.appendChild(js);
}

});


function getUrlVars(pin_URL)
{
    var vars = [], hash;
    var hashes = pin_URL.slice(pin_URL.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

回答by Kamo

The official way to do this is by setting the "data-pin-build" attribute when loading the script:

官方的方法是在加载脚本时设置“data-pin-build”属性:

<script defer="defer" src="//assets.pinterest.com/js/pinit.js" data-pin-build="parsePins"></script>

Then you can render your buttons dynamically like so:

然后你可以像这样动态渲染你的按钮:

// render buttons inside a scoped DOM element
window.parsePins(buttonDomElement);

// render the whole page
window.parsePins();

There is also another method on this site which lets you render them in JavaScript without the script tag.

该站点上还有另一种方法,可以让您在没有脚本标记的情况下在 JavaScript 中呈现它们

回答by Ross Allen

Their pinit.jsfile, referenced in their "Pin it" button docs, doesn't expose any globals. It runs once and doesn't leave a trace other than the iframe it creates.

他们的pinit.js文件,在他们的“Pin it”按钮文档中引用,没有公开任何全局变量。它运行一次,除了它创建的 iframe 之外不会留下任何痕迹。

You could inject that file again to "parse" new buttons. Their JS looks at all anchor tags when it is run and replaces ones with class="pin-it-button"with their iframe'd button.

您可以再次注入该文件以“解析”新按钮。他们的 JS 在运行时查看所有锚标记,并用class="pin-it-button"iframe 按钮替换它们。