我怎样才能从 p 标签中获取文本并将其插入 href 链接中



我的页面上有一个推特按钮,点击它会带你到推特页面,在那里你有文本区域来输入你的消息。我希望用户在单击"推特"按钮时将他们带到推特,并且

页面上标签中的文本会自动插入到文本区域中。这是我的按钮

<div id="twitter-btn" class="center">
<a class="btn btn-info btn-social btn-twitter " href="https://twitter.com/intent/tweet?text=" target="_blank">
<i class="fa fa-twitter"> Twitter</i>
</a> 
</di>

现在Twitter提供了他们自己的按钮和如何使用它的文档。

<a class="twitter-share-button"
href="https://twitter.com/intent/tweet?text=Hello%20world">
Tweet</a>

请注意字符串是如何附加到 URL 末尾的...这是推特按钮文档 https://dev.twitter.com/web/tweet-button 我有一个 id 为"内容"的div 并插入了一个

段落。如何从段落中抓取文本并附加到推特网址。这是关于 codepne.io 的项目 https://codepen.io/zentech/pen/ZyyGgq?editors=1000

首先,您不应该隐藏需要帮助的按钮。

检查此代码笔

代码:

$('.btn-twitter').on( 'click', function( evt ){
evt.preventDefault();
var tweetURL = 'https://twitter.com/intent/tweet?text=' + encodeURIComponent( $('p.sub_text').text() );
window.open(tweetURL, '_blank');
} )

要在运行时(onclick)完成此操作,除了阻止默认超链接操作,然后以JS方式执行此操作外,别无选择。

它的工作方式是,你用一个特殊的GET参数(text)将用户链接到一个特殊的URL(https://twitter.com/intent/tweet),其中包含要预填充推文的文本。

由于你的内容是动态的,你必须使用JavaScript来完成它。您已经在使用 jQuery 来获取引用文本并混合 Twitter 按钮,因此您应该将其添加到您的$('#getMessage').on("click", function() {$("#twitter-btn").show();

var text = encodeURIComponent($('#content').text());
$('#twitter-btn a').attr('href', 'https://twitter.com/intent/tweet?text=' + text);

请注意,您必须使用encodeURIComponent才能使特殊字符(如?, , &, /, ...)正常工作。

改为在javascript中创建链接。

<p id="quote">This is a quote</p>
<button id="tweet" type="button">Tweet</button>

爪哇语

$( "#tweet" ).click(function() {
// make the text url friendly
var text = encodeURI($( "#quote" ).text());
window.location.replace("https://twitter.com/intent/tweet?text=" + text)
});

希望这对你有用。我使用jquery是因为我最熟悉它。我在浏览器中对其进行了测试,它对我有用。

<div id="twitter-btn" class="center">
<button class="btn btn-info btn-social btn-twitter" target="_blank">
<i class="fa fa-twitter"> Twitter</i>
</button> 
</div>
<div id="content">bvnvcbnvbnnb</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script>
$('.btn-twitter').on('click', function(){
var content = $('#content').text();
window.location.href = "https://twitter.com/intent/tweet?text="+encodeURIComponent(content);
});
</script>

最新更新