[英]How to append a div with script tag into an li tag?
We have a <ul>
with many <li>
tags that is used for a menu links. 我们有一个
<ul>
,其中包含许多<li>
标签,这些标签用于菜单链接。 How can we append the following code to the end of the <ul>
? 我们如何将以下代码附加到
<ul>
的末尾?
Problem: 问题:
My current code is not adding even the <div>
tag. 我当前的代码甚至没有添加
<div>
标签。
Goal: Always append the <li><div><script></script></div></li>
as the very last item of the <ul class="menu" id="footer-menu">
by first creating the <script>
tag and then appending it to the newly created <div>
tag and then finally appending it to the end of the <ul>
tag. 目标:始终首先将
<li><div><script></script></div></li>
附加为<li><div><script></script></div></li>
<ul class="menu" id="footer-menu">
的最后一项创建<script>
标记,然后将其附加到新创建的<div>
标记,然后最后将其附加到<ul>
标记的末尾。
Current output: 电流输出:
<ul class="menu" id="footer-menu">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
Desired output: 所需的输出:
<ul class="menu" id="footer-menu">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li><div id='somevalue'><script async="async" crossorigin type="text/javascript" src="some-src"></script></div></li>
</ul>
(function() { var scriptTag = document.createElement('script'); scriptTag.type="text/javascript"; scriptTag.async=true; scriptTag.crossOrigin=true; scriptTag.src="some-source"; var divTag = document.createElement('div'); divTag.id='somevalue'; divTag.append(scriptTag); var ulList = document.getElementById('footer-menu'); ulList.append(divTag); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="menu" id="footer-menu"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul>
You are not calling the anonymous function, use this instead: 您不是在调用匿名函数,而是使用此函数:
(function() { var scriptTag = document.createElement('script'); scriptTag.type="text/javascript"; scriptTag.async=true; scriptTag.crossOrigin=true; scriptTag.src="some-source"; var divTag = document.createElement('div'); divTag.id='somevalue'; divTag.append(scriptTag); var liTag = document.createElement('li'); liTag.append(divTag); var ulList = document.getElementById('footer-menu'); ulList.append(liTag); })();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="menu" id="footer-menu"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul>
Use the lastChild property of the ul. 使用ul的lastChild属性。
Try changing the last line to: 尝试将最后一行更改为:
ulList.lastChild.append(divTag);
以下解决方案会将带有script
标签的div
附加到所需的li
标签中:
$("#footer-menu li").last().append('<div id="somevalue"><script async="async" crossorigin type="text/javascript" src="some-src"></script></div>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.