简体   繁体   English

jQuery防止子记录

[英]jQuery prevent child records

I have a nav that i need to add a <br> dynamically because the CMS we are using doesn't allow for this. 我有一个导航,我需要动态添加<br>因为我们正在使用的CMS不允许这样做。

But it is affecting all of the child elements on the drop down. 但这会影响下拉菜单中的所有子元素。

Here is the basic HTML 这是基本的HTML

<li class="dropdown yamm-fw" id="tab1"><a href="#" data-toggle="dropdown" class="dropdown-toggle">Shop By Brand</a>
  <ul class="dropdown-menu">
       <ul class="col-sm-2 megaDropDown">
          <li><a href="#">List Item</a></li>
          <li><a href="#">List Item</a></li>
          <li><a href="#">List Item</a></li>
          <li><a href="#">List Item</a></li>
          <li><a href="#">List Item</a></li>
          <li><a href="#">List Item</a></li>
       </ul>
  </ul>
</li>

And here is the js that is adding the <br> 这是添加<br>

$(function(){
    $('#tab1 a').each(function( index ) {
        var aHtml = $(this).html();
        var pos = aHtml.lastIndexOf(' ');
        aHtml = aHtml.substring(0,pos) + '<br/>' + aHtml.substring(pos+1)
        $(this).html(aHtml);
    });
});

But i want it to affect tab1 a only nothing on the dropdown. 但是我希望它对tab1的下拉列表没有任何影响。 I have a fiddle created here http://jsfiddle.net/6CTY8/ 我在这里创建了一个小提琴http://jsfiddle.net/6CTY8/

$('#tab1 > a').each(function( index ) {

Using > will make sure only direct descendants are used. 使用>将确保仅使用直接后代。

Here is a fiddle too. 这也是一个小提琴。 http://jsfiddle.net/6CTY8/2/ http://jsfiddle.net/6CTY8/2/

Use child selector . 使用child selector

From Docs: 从文档中:

Selects all direct child elements specified by "child" of elements specified 
by "parent".

Try this: 尝试这个:

$('#tab1 > a').each(function( index ) {
        //YOUR CODE GOES HERE
});

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM