如何在过滤时让jquery忽略id

时间:2017-04-01 21:38:04

标签: jquery

我在内容div中搜索所有ID并在href之前添加。我不能预测孩子的ids会是什么,所以无论如何都要预先设定。

如何让jquery搜索dom但忽略cetain div的id和它的孩子?

           $('*[id]').each(function() {
            var selectVariable = this;
            $(selectVariable).prepend('<a href="#" class="" id="' + $(selectVariable).attr('id') + '">*</a>');
        });

        <div id='content'>
             <!-- How do I stop the jquery from prepending  `id='I can predict'` and all its children-->
            <div id='I can predict'>
                 <div id='I can't predict'>
                 </div>

                  <div id='I can't predict'>
                  </div>
            </div>

            <div id='another piece of content'>
                  <div id='I can't predict (but needs an a link)'>
                  </div>
            </div>
        </div>

2 个答案:

答案 0 :(得分:1)

您可以使用.not($('#I_can_predict, #I_can_predict *'))排除您想要的部分:

$('*[id]').not($('#I_can_predict, #I_can_predict *')).each(function() {
    var selectVariable = this;
    $(selectVariable).prepend('<a href="#" class="" id="' 
                              + $(selectVariable).attr('id') + '">*</a>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='content'>
    content
     <!-- How do I stop the jquery from prepending  `id='I can predict'` and all its children-->
    <div id='I_can_predict'>I can predict
         <div id="I_can't_predict">I can't predict1
         </div>

          <div id="I_can't_predict2">I can't predict2
          </div>
    </div>

    <div id='another_piece_of_content'>another piece of content
          <div id="I_can't_predict_(but_needs_an_a_link)">I_can't_predict_(but_needs_an_a_link)
          </div>
    </div>
</div>

答案 1 :(得分:0)

检查div是否具有ID“I_can_predict”或者其父母是否具有此ID:

if (!$(selectVariable).parents('#I_can_predict').length &&
    selectVariable.id != 'I_can_predict') {
       $(selectVariable).prepend('<a href="#" class="" id="' + $(selectVariable).attr('id') + '">*</a>');
    }

这是一个小提琴: https://jsfiddle.net/7kmc09av/