Combine two similar jQuery scripts into an if/then script

前端 未结 1 357
隐瞒了意图╮
隐瞒了意图╮ 2021-01-27 19:11

I am trying to combine two jQuery loops, based on code from questions answered here, which remove images and iframes from WordPress posts and move them either to new divs or to

相关标签:
1条回答
  • 2021-01-27 19:47

    1) Use $('section:not(#clients)') instead of $('section !#clients')

    2) You do not need to have jQuery("document").ready (function($){ ... }); twice. You can put all script in only one. And you do neither need to declare var matchesEl twice if it still have the same content on second time.

    3) Semantically, if you are using a id called clients you must have only one #clients on your page, so no need for a each() function in that element.

    The code above should do the trick:

    jQuery("document").ready (function($){
    // Elements you want to match
    var matchesEl = "img, iframe"
    
    // For each section [I have added a 'not-#clients' selector, which doesn't work but gives an idea of the logic I'm attempting], get its index number and do the following:
        $('section:not(#clients)').each(function(index){
    
            //If there is a matched element (for each section),
            if ($(this).find(matchesEl).length > 0) {
    
              // create a div.royalSlider and prepend to this section
              $('<div>', {'class': 'royalSlider'}).prependTo(this)
    
              // For each matched element into this section (we don't need to get index number here), 
              $(this).find(matchesEl).each(function() {
    
                // add .rsImg class to this element and insert on the div.royalSlider,
                // not any div.royaSlider, but that one with equivalent index given before
                $(this).addClass('rsImg').appendTo($('section .royalSlider').eq(index));
    
              });
    
            }
    
        });
    
        //No need for each() here (neither index)
        // If there is a matched element in #clients, do:
        if ($('#clients').find(matchesEl).length > 0) {
    
          // Append <ul> to #clients
          $('<ul>').appendTo($('#clients'));
    
          // For each matched element into #clients
          $('#clients').find(matchesEl).each(function() {
    
            //Create a <li>, append the element content into <li> and insert it on <ul> into #clients
            $("<li>").append($(this)).appendTo($('#clients').children('ul'));
    
          });
    
        }
    
    
        $('p').filter(function () { return $.trim(this.innerHTML) == "" }).remove();
    
    });
    
    0 讨论(0)
提交回复
热议问题