问题
I have a tiny bit of script that allows the user to resize the window to convert an unordered list into a select menu.
However, I'd like to remove any nested unordered lists from the select menu.
DEMO: http://jsfiddle.net/k7272/
So basically using the example above, the part 'test' wouldn't appear in the select menu, but would still appear in unordered list.
How do I achieve this?
Here is my Javascript:
// DOM ready
$(function() {
// Create the dropdown base
$("<select />").appendTo("nav");
// Create default option "Go to..."
$("<option />", {
"selected": "selected",
"value" : "",
"text" : "Go to..."
}).appendTo("nav select");
// Populate dropdown with menu items
$("nav a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("nav select");
});
// To make dropdown actually work
// To make more unobtrusive: http://css-tricks.com/4064-unobtrusive-page-changer/
$("nav select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
Many thanks :-D
回答1:
targeting nav a will find all its children and even children of children, so you need to directly target them like this
$("nav > ul > li > a").each(...
http://jsfiddle.net/k7272/1/
回答2:
Change the selector to only look for direct children, this will avoid the nested ul. Try this:
$("nav > ul > li > a").each(function () {
// your code...
});
Updated fiddle
回答3:
Instead of the "nav a" selector, which selects any descendant of , use the child operator: $("nav>ul>li>a").
Better yet, put a class on your top level ul and then use $('ul.classname>li>a'), then you can move the whole list around your DOM and still have the selector work.
来源:https://stackoverflow.com/questions/17470177/remove-list-items-from-select-menu-with-jquery