我正在尝试动态生成一个链接以在 Twitter 上发布推文,然后像这样单击它...
$("body").prepend("<a id=\"twitter_link\" href='https://twitter.com/intent/tweet'></a>");
$( "#twitter_link" ).click(function() {
console.log( "Handler for .click() called." );
});
这不起作用,我哪里出错了?
最佳答案
您的代码已完成 99%!
您的新 a
元素没有文本
重要
The click event it's necessary if you need to execute a logic when the new link is clicked, otherwise, that event it's unnecessary.
$("body").prepend("<a id=\"twitter_link\" href='https://twitter.com/intent/tweet'>Hello World</a>");
$( "#twitter_link" ).click(function(e) {
e.preventDefault(); //This is just to show your logic is working!
console.log( "Handler for .click() called." );
location.href = this.href; //This is to redirect to the specific page after any previous executed logic.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
资源
关于javascript - jQuery - 创建链接元素并单击它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48696637/