将一个菜单代码转换为另一个

时间:2014-08-11 11:23:26

标签: jquery html

我有服务器生成的这个菜单,我无法自定义。第二级以上是单独的div

<div>
    <ul class='....'>
        <li id='......'>
            <a href='/'>Home</a>
        </li>
        <li id='..................'>
            <a href='/about.html'>About</a>
            <div class='.........' style='display:none'>
                <ul class='..........'>
                    <li id='..............'>
                        <a href='/services.html' >
                            <span class='.............'>Services</span>
                        </a>
                    </li>
                    <li id='...............'>
                        <a href='/costs.html' >
                            <span class='...........'>Costs</span>
                        </a>
                    </li>
                    <li id='................'>
                        <a href='/terms--conditions.html' >
                            <span class='............'>Terms & Conditions</span>
                        </a>
                    </li>
                </ul>
            </div>
        </li>
        <li id='.................'>
            <a href='/contact.html'>Contact</a>
        </li>
    </ul>
</div>

但我希望在页面加载时使用jQuery进行操作。还会生成我想要删除的类和ID。以下是运行代码后的样子:

<div>
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/about.html">About</a>
            <ul>
                <li><a href="/services.html">Services</a>

                </li>
                <li><a href="/costs.html">Costs/a>

                </li>
                <li><a href="/terms--conditions.html">Terms & Conditions</a>

                </li>
            </ul>
        </li>
        <li id="new-media-menu"><a href='/contact.html'>Contact</a></li>
    </ul>
</div>

jQuery代码

function cleanMenuSelector(sel) {
    $(sel).removeAttr('class');
    $(sel).children('ul').each(function() {
        cleanMenuSelector($(sel))
    });
    $(sel).removeAttr('id');
}

$("div > ul").each(function() {
    cleanMenuSelector($(this));
})

在JS小提琴上,它给了我错误

Uncaught SyntaxError: Unexpected token } fiddle.jshell.net/_display/:33
Uncaught ReferenceError: $ is not defined
4
Uncaught TypeError: undefined is not a function
3
Uncaught TypeError: undefined is not a function

1 个答案:

答案 0 :(得分:1)

将它放在$ document.ready中,这对我有用!

JSFIDDLE

$(document).ready(function(){
   function cleanMenuSelector(sel) {
       $(sel).removeAttr('class');
       $(sel).removeAttr('id');
   }

   $("div, ul, li").each(function() {
       cleanMenuSelector($(this));
   })
});