如何使用相同的内容在li和ul上附加类? [英] How to append class on li and ul using same content?

查看:127
本文介绍了如何使用相同的内容在li和ul上附加类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要添加类或从内容中追加类名.这是例子.

I need to addclass or append class name same from content. Here is example.

<ul>
  <li>
    <a href="#">men</a>
    <ul>
      <li><a href="#">new arrival</a></li>
      <li><a href="#">about</a></li>
    </ul>
  </li>
  <li>
    <a href="#">top 2nd menu</a>
    <ul>
      <li><a href="#">go</a></li>
      <li><a href="#">hello menu</a></li>
    </ul>
  </li>
</ul>

这是我想要的最终结果加载:

Here is what I want as final result onload:

<ul>
  <li class="men">
    <a href="#">men</a>
    <ul>
      <li class="new-arrival"><a href="#">new arrival</a></li>
      <li class="about"><a href="#">about</a></li>
    </ul>
  </li>
  <li class="top-2nd-menu">
    <a href="#">top 2nd menu</a>
    <ul>
      <li class="go"><a href="#">go</a></li>
      <li class="hello-menu"><a href="#">hello menu</a></li>
    </ul>
  </li>
</ul>

推荐答案

您可以用一点JQ来做到这一点.

you can do this with a little JQ .

A..首先,您需要找到与每个li相对应的每个atext表单.

A. first you need to find the text form each a that corresponds to each li.

使用text()函数(此处的信息))来做到这一点 >

B.,那么如果您有多个单词作为text,则需要使用replace()方法(此处的信息).

B. then if you have more than one word as text you need to join the words with - using the replace() method (info here).

这是因为,如果不连接单词(在单词之间加上-"),例如对于文本top 2nd menu,则li将具有3个单独的类,而不仅仅是一个类.因此,通过使用replace()方法,您可以获得所需的结果,分别为top-2nd-menu

this is because if you don't join the words ( put "-" between them ), for example for text top 2nd menu then the li will have 3 separate classes instead of only one. so by using the replace() method you get the wanted result, respectively top-2nd-menu

C.,然后使用attr("class","nav-" + addcl)将类添加到您的li中( 信息在这里 )

C. and then add class to your li with attr("class","nav-" + addcl) ( info here )

通过这种方式,您可以在从A点和B点获得的文本(addcl)之前添加所需的任何单词

this way you add whichever word you want before the text ( addcl ) you got from points A and B

$("li").each(function(){


var litext = $(this).children("a").text()
var addcl = litext.replace(/\s/g, '-').toLowerCase()
$(this).attr('class', 'nav-' +  addcl);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li><a href="#">men</a>
      <ul>
      <li><a href="#">new arrival</a></li>
      <li><a href="#">about</a></li>
      </ul>
    </li>
    <li><a href="#">top 2nd menu</a>
      <ul>
      <li><a href="#">go</a></li>
      <li><a href="#">hello menu</a></li>
      </ul>
    </li>
</ul>

这篇关于如何使用相同的内容在li和ul上附加类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆