Combine two similar jQuery scripts into an if/then

2019-03-05 10:35发布

问题:

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 new lists. My previous questions have sought to achieve each of these outcomes independently, but I now need to combine them in a single page, selecting which one to use based on the parent container.

Specifically, I want the first script to run on all <section> containers apart from the one with the #clients ID. That one should use the second script.

I imagine I probably need some kind of if/then logic which runs the code appropriate to the selector, but am having a hard time achieving this. Currently, one script is breaking the other.

Here are the two scripts - please note the comment in parentheses on line 4:

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 !#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));

  });

}

});
});

jQuery("document").ready (function($){
var matchesEl = "img, iframe"

$('section #clients').each(function(index){

if ($(this).find(matchesEl).length > 0) {

  $('<ul>').appendTo($('section');

  $(this).find(matchesEl).each(function() {
    //The line code under will only works if all your <section>s always have at least one matched element.
    //$("<li>").append($(this)).appendTo($('section ul').eq(index));
    //So the right code is:
    $("<li>").append($(this)).appendTo($('section').eq(index).children('ul'));
  });

}
$('p').filter(function () { return $.trim(this.innerHTML) == "" }).remove();
});
});

Rather than running two scripts that clash, I need to develop one script that selectively runs based on the jQuery selector.

I would attempt to write this unified script and post it here, rather than showing the two, but currently the second script (which attempts to create <ul> elements) does not work at all, and I am not sure how to get that working alone, which would seem to be a prerequisite for combining them.

If it helps, the site I am working on can be viewed (in developmental stages!) here.

Many thanks in advance for any help with this.

回答1:

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();

});