首页 > 解决方案 > 如何在 jquery 中将 h1 标签添加到 $('a')

问题描述

此代码显示在 jquery 测验的最后阶段。它在我的网站上的格式不正确(可能与我的 CMS 有点冲突),但 h1 标签是我想要的格式。

如何使这也使 a href 成为 h1 标签?

$('<a>')
.addClass('#subscribetext')
.attr('id','subscribetext')
.attr('href','https://www.hamsterdance.org/subscribe')
.html('')
.text('Sign me up!')
.insertAfter('#tweetresult'); 

标签: javascriptjquery

解决方案


使用.append()与不使用.text()

如果你使用.text('<h1>Sign me up!</h1>')它会显示<h1>Sign me up!</h1>
,但如果你使用.append('<h1>Sign me up!</h1>')它会显示

给我报名!

$('<a>')
.addClass('subscribetext')
.attr('id','subscribetext')
.attr('href','https://www.hamsterdance.org/subscribe')
.append('<h1>Sign me up!</h1>')
.insertAfter('#tweetresult'); 

演示

$('<a>')
.addClass('subscribetext')
.attr('id','subscribetext')
.attr('href','https://www.hamsterdance.org/subscribe')
.append('<h1>Sign me up!</h1>')
.insertAfter('#tweetresult'); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tweetresult"></div>


推荐阅读