2016-04-05 2 views
2

Я использую Twitter createShareButton на моем сайте (http://conn3cted.uk.tn/quote.html), но каждый раз, когда нажата кнопка «Новая цитата», создается новая кнопка Twitter, оставляя меня с несколькими кнопками (например, если Кнопка «Новая котировка» нажата 10 раз, будет 10 кнопок общего доступа).Кнопка Twitter создает несколько кнопок

Он работал отлично пару дней назад, поэтому не уверен, что, черт возьми, произошло.

My JavaScript ниже

// Random Quote Generator 
$(document).ready(function() { 
    // Set the default values for future AJAX requests 
    $.ajaxSetup({ 
    // Prevent all future AJAX requests from being cached. 
    cache: false 
    }); 
    // API URL 
    var quoteURL = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1"; 
    // getQuote function, which accepts a data parameter. 
    var getQuote = function(data) { 
    // Replace the html of the targeted element with the returned content field. 
    $(".quoteContent").html(data[0].content); 
    // Replace the html of the targeted element with the returned title field. 
    $(".quoteTitle").html('Author: ' + data[0].title); 
    newColor(); 

    twttr.ready(function() { 
     // Use the pre-made createShareButton function 
     twttr.widgets.createShareButton(
      // Do not share a URL 
      " ", 
      // Div where the share button should be inserted 
      document.getElementById('tweetButton'), 
      { 
       // Define the tweet that will be used 
       text: "'" + $(".quoteContent").text().replace(/(\r\n|\n|\r)/gm,"") + "'\n" + 
       $(".quoteTitle").text(), 
       // Set the size of the Twitter share button 
       size: "large", 
      } 
     ); 
    }); 
    }; 

    var newColor = function() { 
    var color = Please.make_color(); 
    $("body, button, .btn").css("background-color",color); 
    $("p, blockquote").css("color",color); 
    }; 

    /* 
    * On every page load get JSON data from the URL, defined in the 
    * 'url' variable, and then run the getQuote function 
    */ 
    $.getJSON(quoteURL, getQuote); 
//newColor(); 

/* 
    * When the button is clicked load get JSON data from the * URL,defined in the 'url' variable, and then run the 
    * getQuote function. 
    */ 
    $(".regenButton").click(function() { 
    $.getJSON(quoteURL, getQuote); 
    }); 


}); 

ответ

1

Это потому, что вы создали кнопку твиттера в своем обратном вызове $.getJSON. Поэтому при каждом загрузке цитаты создается кнопка твиттера.

Лучшим решением было бы создать кнопку один раз и обновить общий текст при загрузке котировки. Который я не могу найти в документах. Поэтому я предпочитаю сначала удалить первый:

var getQuote = function(data) { 
    // Replace the html of the targeted element with the returned content field. 
    $(".quoteContent").html(data[0].content); 
    // Replace the html of the targeted element with the returned title field. 
    $(".quoteTitle").html('Author: ' + data[0].title); 
    newColor(); 

    // remove previous button 
    $('.twitter-share-button').remove(); 

    // and create a new one 
    twttr.ready(function() { 
     // Use the pre-made createShareButton function 
     twttr.widgets.createShareButton(
      // Do not share a URL 
      " ", 
      // Div where the share button should be inserted 
      document.getElementById('tweetButton'), 
      { 
       // Define the tweet that will be used 
       text: "'" + $(".quoteContent").text().replace(/(\r\n|\n|\r)/gm,"") + "'\n" + 
       $(".quoteTitle").text(), 
       // Set the size of the Twitter share button 
       size: "large", 
      } 
    ); 
    }); 
}; 
+0

Ах, ладно! Поэтому он не понимает, что он должен только создать один - я думаю, что я запутывал настройку виджета HTML (что он делает это только один раз) с тем, что эта кнопка также не должна создавать несколько. Но это имеет смысл - это создание новой кнопки, как было сказано, просто добавив ее к указанному 'div' . Я добавил, что дополнительная строка и все работает сейчас :-) спасибо! Как вы можете сказать, я все еще учусь. Иногда я делаю глупые ошибки. – OmisNomis

+0

Добро пожаловать, и, похоже, вы сейчас понимаете проблему! Удачи. – Pimmol

2

Ваш твиттер код кнопки доля находится внутри функции getQuote - поэтому каждый раз .regenButton щелкают, getQuote называется, что дает вам еще одну кнопку.

+1

Ах право в порядке! В этом есть смысл. Где подходящее место для выполнения этой функции? Я попытался добавить его под '$ .getJSON (quoteURL, getQuote) ;, но он не вытащил созданную цитату. – OmisNomis

+0

, вероятно, потому, что ваша кнопка щебня ссылается на '.quoteContent', который не имеет никакого контента до нажатия кнопки кавычки ... вы могли бы либо удалить предыдущую кнопку Twitter, до ее создания, либо посмотреть на api, чтобы узнать, можете ли вы измените его содержимое после. – Stuart

+0

Спасибо за помощь :) Я смог удалить и воссоздать кнопку с помощью @Pimskie – OmisNomis

0

Для всех, кто сталкивается с этим постом; Я изучал это немного больше и обнаружил способ создания кнопки Twitter Share без использования виджета Twitter.

Прежде всего, необходимо создать Ярлык ...

<!-- 
- href will create a link to the Twitter web intent composer 
- target (_blank) will open the link in a new window 
--> 
<a class="tweetButton" href="https://twitter.com/intent/tweet?text=Initial Text" 
       target="_blank"> 
<!-- Create a button for the link to interact with --> 
    <button class="btn"> 
     Tweet 
    </button> 
</a> 

А затем настроить JQuery изменить его для каждого нового предложения ...

/* 
* Amend the "href" attribute of the element with a "tweetButton" class 
* (the "a" tag) to take the twitterURL Global Variable, plus the parameter 
* "text=" (which specifies what the tweet will say) and assign the value of: 
* 
* - the element with a class of "quoteContent", without the HTML tags 
* (.text()), removing all line breaks (.replace(/(\r\n|\n|\r)/gm,"")), 
* trims all the white space (.trim()) 
* 
* - adds a line break (\n) 
* 
* - the element with a class of "quoteTitle", without the HTML tags 
* (.text()) 
* 
* Then URL encode the result (encodeURIComponent) to complete the amendment 
*/ 
$(".tweetButton").attr("href", twitterURL + "text=" + encodeURIComponent("'" + 
    $(".quoteContent").text().replace(/(\r\n|\n|\r)/gm,"").trim() + 
    "'\n" + $(".quoteTitle").text())); 
Смежные вопросы