使用jquery根据来自API的输入数据动态更改Twitter按钮的data-text属性的值

Changing the value of data-text attribute of the Twitter button dynamically based on input data from an API using jquery

本文关键字:Twitter 按钮 属性 data-text 动态 输入 jquery 使用 API 数据      更新时间:2023-09-26

我设计了一个页面,在这里点击按钮"Get Quote"将在一个div中显示各种报价,这些报价是从API获得的。我想添加一个twitter分享按钮。但是我真的很困惑如何改变twitter按钮的"data-text"属性的值,动态地改变API引用的值。我使用jQuery处理来自API的数据,那么我如何使用jQuery更改"data-text"的值呢?

代码是:

HTML:

<body>
  <h1><div id="quotegot" class="well well-lg quote"></div></h1>
  <button type="submit" class="btn btn-success btn-lg" id="quoteid">Get Quote</button>
  <a href="https://twitter.com/share" class="twitter-share-button" data-show-count="false" data-text="hello">Tweet</a><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
</body>

JS:

$("#quoteid").on("click",function(){
    $.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&key=457653&format=json&lang=en",function(quotejson){
        $("#quotegot").html(quotejson["quoteText"]);
    });
});
$(".twitter-share-button").attr("data-text", $(".quote").text());

动态更改推文按钮"data-text"内容

还不能评论,所以放在这里。这里有一个jsfiddle显示它是如何工作的