[英]How to add a submenu after X number of <li> with Javascript or Jquery?
I have in HTML 我有HTML
<div class="ktmsg">
<ul>
<li class="a1">
<a title="Link Tools" href="#"> … </a>
</li>
<li class="a2">
<a title="Link Tools" href="#"> … </a>
</li>
<li class="a3">
<a title="Link Tools" href="#"> … </a>
</li>
</ul>
</div>
What i want to do is to add after the second </li>
an <ul><a href="#">More</a></ul>
Final expected output should be 我想要做的是在第二次
</li>
之后添加<ul><a href="#">More</a></ul>
最终预期输出应该是
<div class="ktmsg">
<ul>
<li class="a1">
<a title="Link Tools" href="#"> … </a>
</li>
<li class="a2">
<a title="Link Tools" href="#"> … </a>
</li>
<ul> //Starting the sub-menu
<a href="#">More</a> // The link that after i hover it will start showing the <li> starting from the third one
<li class="a3">
<a title="Link Tools" href="#"> … </a>
</li>
</ul>
</ul>
</div>
I am thinking that the javascript would look smth like this: 我认为javascript看起来像这样:
limenu = document.selectAll(.ktmsg)('<li>');
for(var i=1, i<2, i++)
remove.limenu
add.
.... And i am quite stuck, Please help, would be much appreciated. ....我很困惑,请帮助,非常感谢。
Using jQuery 使用jQuery
jQuery(function ($) {
var $lis = $('.ktmsg > ul > li');
var $a = $('<li><a href="#">More</a></li>').insertAfter($lis.eq(1));
var $lefts = $lis.slice(2).hide();
$a.hover(function () {
clearTimeout($a.data('hoverTimer'));
$lefts.show();
}, function () {
var timer = setTimeout(function () {
$lefts.hide();
}, 200);
$a.data('hoverTimer', timer);
});
$lefts.hover(function () {
clearTimeout($a.data('hoverTimer'));
}, function () {
var timer = setTimeout(function () {
$lefts.hide();
}, 200);
$a.data('hoverTimer', timer);
});
})
With jQuery to add this: 用jQuery添加这个:
<ul><a href="#">More</a></ul>
after second li you need: 在第二个李之后你需要:
$( 'li:eq(1)' ).after( '<ul><a href="#">More</a></ul>' );
I've created a fiddle of how this could work using jQuery. 我已经创建了一个如何使用jQuery 工作的小提琴 。 Pretty simple really, you just hide the sub menu using CSS and then show/hide it as needed using jQuery when "More" is being hovered over.
非常简单,你只需使用CSS隐藏子菜单,然后在“更多”悬停时使用jQuery根据需要显示/隐藏它。 I've used
fadeIn()
and fadeOut()
but you could just as easily use hide()
and show()
if you don't need the animations. 我已经使用了
fadeIn()
和fadeOut()
但如果你不需要动画,你可以很容易地使用hide()
和show()
。 I've restructured your HTML slightly so if you use my solution use my new HTML. 我稍微重构了你的HTML,所以如果你使用我的解决方案使用我的新HTML。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.