Wymyśliłem to. Oto jak to zrobić.
Ogólna idea jest:
- w HTML ustawić
class
swojego <a>
dla przycisku Udostępnij Twitter być coś innego niż .twitter-share-button
. Podaj także <a>
a style="display:none;"
.
- W HTML, w miejscu, w którym ma pojawić się przycisk udostępniania Twittera, utwórz
<div>
(lub <span>
) z unikalnym id
.
- W swojej jQuery, gdy chcesz ustawić dane dla przycisku Udostępnij Twitter będzie:
- „clone()
the hidden, mis-named,
` tag od kroku # 1
- Z tego klonu, ustaw
data-url
etc. .. atrybuty jak chcesz
- Usuń atrybut
style
z klonu (odkryć go)
- Zmiana
class
klonu do twitter-share-button
append()
ten klon do swojego <div>
z kroku 2.
- Użyj
$.getScript()
, aby załadować i uruchomić skrypt JavaScript na Twitterze. Spowoduje to konwersję sklonowanego <a>
do ze wszystkimi prawymi goop.
Oto mój HTML (w Jade):
a.twitter-share-button-template(style="display:none;", href='https://twitter.com/share=', data-lang='en',
data-url='http://urlthatwillbe_dynamically_replaced',
data-via='ckindel', data-text='Check this out!',
data-counturl='http://counturlthatwillbe_dynamically_replaced') Share with Twitter
#twitter-share-button-div
Następnie w swoim js po stronie klienta:
// the twitter share button does not natively support being dynamically
// updated after the page loads. We want to give it a unique (social_id)
// link whenver this modal is shown. We engage in some jQuery fun here to
// clone a 'hidden' twitter share button and then force the Twitter
// Javascript to load.
// remove any previous clone
$('#twitter-share-button-div').empty()
// create a clone of the twitter share button template
var clone = $('.twitter-share-button-template').clone()
// fix up our clone
clone.removeAttr("style"); // unhide the clone
clone.attr("data-url", someDynamicUrl);
clone.attr("data-counturl", someDynamicCountUrl);
clone.attr("class", "twitter-share-button");
// copy cloned button into div that we can clear later
$('#twitter-share-button-div').append(clone);
// reload twitter scripts to force them to run, converting a to iframe
$.getScript("http://platform.twitter.com/widgets.js");
mam główne wskazówki dotyczące tego rozwiązania stąd: http://tumblr.christophercamps.com/post/4072517874/dynamic-tweet-button-text-using-jquery
Próbuję osiągnąć w zasadzie to samo. Próbowałem dynamicznie aktualizować atrybut 'data-url' za pomocą następującego:' $ ('. Twitter-share-button') .attr ("adres danych", "http: // mynewlink"); 'ale program Twitter javascript ma już działa i to nie działa. Wsparcie! – tig