繁体   English   中英

向文档添加字体真棒按钮

[英]adding a font awesome button to the document

我想向按钮添加一个字体很棒的符号,然后将该按钮附加到我的页面。 到目前为止我的代码:

var rem=document.createElement("button");
rem.setAttribute('value','<i class="fa fa-trash-o" aria-hidden="true"></i>');
document.appendChild(rem);

但它不起作用。 控制台上有这个错误:

无法在“节点”上执行“appendChild”:文档中只允许一个元素。

那么我如何实现这一目标? 我可以使用其他代码,例如 jQuery 等

两件事情...

第一个是您尝试将图标添加到按钮的方式。 通过使用rem.set('value', '...')你基本上是说输出应该是

<button value="<i class="fa fa-trash-o" aria-hidden="true"></i>"></button>

……但你真正想要的是……

<button><i class="fa fa-trash-o" aria-hidden="true"></i></button>

要实现此目的,请使用rem.innerHTML = '...'

其次,您正在尝试附加到无效的文档,这就是为什么您收到错误“无法在 'Node' 上执行 'appendChild':仅允许文档中的一个元素。”。

你想要的是将它附加到<body>或页面上的另一个元素,你可以用document.body.appendChild(rem)来做到这一点。 请参阅下面的解析代码。

var rem = document.createElement('button');
    rem.innerHTML = '<i class="fa fa-trash-o" aria-hidden="true"></i>';
document.body.appendChild(rem);

如果您已经在使用 jQuery,则可以执行以下操作...

var rem = $( '<button><i class="fa fa-trash-o" aria-hidden="true"></i></button>' );
$('body').append(rem);

希望这可以帮助!

你在这里有两个问题。 首先,错误的原因是因为您无法将button元素附加到document 您需要将其附加到body的元素。 在下面的示例中,我使用了body本身,但任何都可以。

其次,您需要将包含图标的<i>元素设置为您创建的button元素,而不是value属性。

 var rem = document.createElement("button"); rem.innerHTML = '<i class="fa fa-trash-o" aria-hidden="true"></i>'; document.body.appendChild(rem);
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM