I am working on a website which needs to be responsive. I want to convert the navigation into a <select>
. There can be any number of <nav>
and any number of <ul>
inside<nav>
. I have used for loops
to calculate number of <nav> and <ul> inside <nav>
.
我正在一个需要响应的网站上工作。我想将导航转换为
One is generating and the other one is not generating, please help me out to resolve this.
一个是生成而另一个没有生成,请帮我解决这个问题。
这是jsfiddle
1 个解决方案
#1
1
It does not work, because you're looking for .children('ul')
and this only includes immediate descendants, however your second nav
has a div
wrapped around the ul
...
它不起作用,因为你正在寻找.children('ul'),这只包括直接的后代,但是你的第二个导航有一个div包裹在ul ...
You could change .children
call to .find
which looks for descendants at any depth
你可以改变.children调用.find来查找任何深度的后代
-- CUT HERE --
- 剪这里 -
Alternative solution:
$('nav').each(function(navIndex, navElement) {
$(this).find('ul').each(function(ulIndex, ulElement) {
var $sel = $('<select name="nav'+navIndex+'-'+ulIndex+'" />');
$sel.append('<option value="#">Go to...</option>');
$sel.change(function() { document.location.href = this.value; });
$(this).find('li>a').each(function(aIndex, aElement) {
$sel.append('<option value="' + this.href + '">' + $(this).text() + '</option>');
});
$(this).after($sel); // place this select after the ul...
});
});
#1
1
It does not work, because you're looking for .children('ul')
and this only includes immediate descendants, however your second nav
has a div
wrapped around the ul
...
它不起作用,因为你正在寻找.children('ul'),这只包括直接的后代,但是你的第二个导航有一个div包裹在ul ...
You could change .children
call to .find
which looks for descendants at any depth
你可以改变.children调用.find来查找任何深度的后代
-- CUT HERE --
- 剪这里 -
Alternative solution:
$('nav').each(function(navIndex, navElement) {
$(this).find('ul').each(function(ulIndex, ulElement) {
var $sel = $('<select name="nav'+navIndex+'-'+ulIndex+'" />');
$sel.append('<option value="#">Go to...</option>');
$sel.change(function() { document.location.href = this.value; });
$(this).find('li>a').each(function(aIndex, aElement) {
$sel.append('<option value="' + this.href + '">' + $(this).text() + '</option>');
});
$(this).after($sel); // place this select after the ul...
});
});