如果条件在javascript中无法正常工作

时间:2016-03-15 05:00:11

标签: javascript jquery

我所拥有的是用于图像的灯箱的java脚本,并且工作正常。

当图片标记中缺少&#alt; alt属性时会出现问题'脚本无法正常工作。 但是,如果他们是img标签中的&#; alt属性,甚至是空白'脚本工作正常。 因此,我想在其上添加条件,以便如果&#;; alt属性丢失或空白'然后显示文字' No Caption'。

感染功能:

    // CAPTION

captionOn = function() {
  var description = $('a[href="' + $('#imagelightbox').attr('src') + '"] img').attr('alt');
  if (description.length > 0)
    $('<div id="imagelightbox-caption">' + description + '</div>').appendTo('body');
},
captionOff = function() {
  $('#imagelightbox-caption').remove();
},

我创建了一个代码段,请检查出来或https://jsfiddle.net/Bloggerz/a9yary1x/

如有任何其他细节,请发表评论。

&#13;
&#13;
;
(function(e, t, n, r) {
  "use strict";
  var i = function() {
      var e = n.body || n.documentElement,
        e = e.style;
      if (e.WebkitTransition == "") return "-webkit-";
      if (e.MozTransition == "") return "-moz-";
      if (e.OTransition == "") return "-o-";
      if (e.transition == "") return "";
      return false
    },
    s = i() === false ? false : true,
    o = function(e, t, n) {
      var r = {},
        s = i();
      r[s + "transform"] = "translateX(" + t + ")";
      r[s + "transition"] = s + "transform " + n + "s linear";
      e.css(r)
    },
    u = "ontouchstart" in t,
    a = t.navigator.pointerEnabled || t.navigator.msPointerEnabled,
    f = function(e) {
      if (u) return true;
      if (!a || typeof e === "undefined" || typeof e.pointerType === "undefined") return false;
      if (typeof e.MSPOINTER_TYPE_MOUSE !== "undefined") {
        if (e.MSPOINTER_TYPE_MOUSE != e.pointerType) return true
      } else if (e.pointerType != "mouse") return true;
      return false
    };
  e.fn.imageLightbox = function(r) {
    var r = e.extend({
        selector: 'id="imagelightbox"',
        allowedTypes: "png|jpg|jpeg|gif",
        animationSpeed: 250,
        preloadNext: true,
        enableKeyboard: true,
        quitOnEnd: false,
        quitOnImgClick: false,
        quitOnDocClick: true,
        onStart: false,
        onEnd: false,
        onLoadStart: false,
        onLoadEnd: false
      }, r),
      i = e([]),
      l = e(),
      c = e(),
      h = 0,
      p = 0,
      d = 0,
      v = false,
      m = function(t) {
        return e(t).prop("tagName").toLowerCase() == "a" && (new RegExp(".(" + r.allowedTypes + ")$", "i")).test(e(t).attr("href"))
      },
      g = function() {
        if (!c.length) return true;
        var n = e(t).width() * .8,
          r = e(t).height() * .9,
          i = new Image;
        i.src = c.attr("src");
        i.onload = function() {
          h = i.width;
          p = i.height;
          if (h > n || p > r) {
            var s = h / p > n / r ? h / n : p / r;
            h /= s;
            p /= s
          }
          c.css({
            width: h + "px",
            height: p + "px",
            top: (e(t).height() - p) / 2 + "px",
            left: (e(t).width() - h) / 2 + "px"
          })
        }
      },
      y = function(t) {
        if (v) return false;
        t = typeof t === "undefined" ? false : t == "left" ? 1 : -1;
        if (c.length) {
          if (t !== false && (i.length < 2 || r.quitOnEnd === true && (t === -1 && i.index(l) == 0 || t === 1 && i.index(l) == i.length - 1))) {
            w();
            return false
          }
          var n = {
            opacity: 0
          };
          if (s) o(c, 100 * t - d + "px", r.animationSpeed / 1e3);
          else n.left = parseInt(c.css("left")) + 100 * t + "px";
          c.animate(n, r.animationSpeed, function() {
            b()
          });
          d = 0
        }
        v = true;
        if (r.onLoadStart !== false) r.onLoadStart();
        setTimeout(function() {
          c = e("<img " + r.selector + " />").attr("src", l.attr("href")).load(function() {
            c.appendTo("body");
            g();
            var n = {
              opacity: 1
            };
            c.css("opacity", 0);
            if (s) {
              o(c, -100 * t + "px", 0);
              setTimeout(function() {
                o(c, 0 + "px", r.animationSpeed / 1e3)
              }, 50)
            } else {
              var u = parseInt(c.css("left"));
              n.left = u + "px";
              c.css("left", u - 100 * t + "px")
            }
            c.animate(n, r.animationSpeed, function() {
              v = false;
              if (r.onLoadEnd !== false) r.onLoadEnd()
            });
            if (r.preloadNext) {
              var a = i.eq(i.index(l) + 1);
              if (!a.length) a = i.eq(0);
              e("<img />").attr("src", a.attr("href")).load()
            }
          }).error(function() {
            if (r.onLoadEnd !== false) r.onLoadEnd()
          });
          var n = 0,
            u = 0,
            p = 0;
          c.on(a ? "pointerup MSPointerUp" : "click", function(e) {
            e.preventDefault();
            if (r.quitOnImgClick) {
              w();
              return false
            }
            if (f(e.originalEvent)) return true;
            var t = (e.pageX || e.originalEvent.pageX) - e.target.offsetLeft;
            l = i.eq(i.index(l) - (h / 2 > t ? 1 : -1));
            if (!l.length) l = i.eq(h / 2 > t ? i.length : 0);
            y(h / 2 > t ? "left" : "right")
          }).on("touchstart pointerdown MSPointerDown", function(e) {
            if (!f(e.originalEvent) || r.quitOnImgClick) return true;
            if (s) p = parseInt(c.css("left"));
            n = e.originalEvent.pageX || e.originalEvent.touches[0].pageX
          }).on("touchmove pointermove MSPointerMove", function(e) {
            if (!f(e.originalEvent) || r.quitOnImgClick) return true;
            e.preventDefault();
            u = e.originalEvent.pageX || e.originalEvent.touches[0].pageX;
            d = n - u;
            if (s) o(c, -d + "px", 0);
            else c.css("left", p - d + "px")
          }).on("touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel", function(e) {
            if (!f(e.originalEvent) || r.quitOnImgClick) return true;
            if (Math.abs(d) > 50) {
              l = i.eq(i.index(l) - (d < 0 ? 1 : -1));
              if (!l.length) l = i.eq(d < 0 ? i.length : 0);
              y(d > 0 ? "right" : "left")
            } else {
              if (s) o(c, 0 + "px", r.animationSpeed / 1e3);
              else c.animate({
                left: p + "px"
              }, r.animationSpeed / 2)
            }
          })
        }, r.animationSpeed + 100)
      },
      b = function() {
        if (!c.length) return false;
        c.remove();
        c = e()
      },
      w = function() {
        if (!c.length) return false;
        c.animate({
          opacity: 0
        }, r.animationSpeed, function() {
          b();
          v = false;
          if (r.onEnd !== false) r.onEnd()
        })
      };
    e(t).on("resize", g);
    if (r.quitOnDocClick) {
      e(n).on(u ? "touchend" : "click", function(t) {
        if (c.length && !e(t.target).is(c)) w()
      })
    }
    if (r.enableKeyboard) {
      e(n).on("keyup", function(e) {
        if (!c.length) return true;
        e.preventDefault();
        if (e.keyCode == 27) w();
        if (e.keyCode == 37 || e.keyCode == 39) {
          l = i.eq(i.index(l) - (e.keyCode == 37 ? 1 : -1));
          if (!l.length) l = i.eq(e.keyCode == 37 ? i.length : 0);
          y(e.keyCode == 37 ? "left" : "right")
        }
      })
    }
    e(n).on("click", this.selector, function(t) {
      if (!m(this)) return true;
      t.preventDefault();
      if (v) return false;
      v = false;
      if (r.onStart !== false) r.onStart();
      l = e(this);
      y()
    });
    this.each(function() {
      if (!m(this)) return true;
      i = i.add(e(this))
    });
    this.switchImageLightbox = function(e) {
      var t = i.eq(e);
      if (t.length) {
        var n = i.index(l);
        l = t;
        y(e < n ? "left" : "right")
      }
      return this
    };
    this.quitImageLightbox = function() {
      w();
      return this
    };
    return this
  }
})(jQuery, window, document);



$(function() {
  // ACTIVITY INDICATOR

  var activityIndicatorOn = function() {
      $('<div id="imagelightbox-loading"><div></div></div>').appendTo('body');
    },
    activityIndicatorOff = function() {
      $('#imagelightbox-loading').remove();
    },


    // OVERLAY

    overlayOn = function() {
      $('<div id="imagelightbox-overlay"></div>').appendTo('body');
    },
    overlayOff = function() {
      $('#imagelightbox-overlay').remove();
    },


    // CLOSE BUTTON

    closeButtonOn = function(instance) {
      $('<button type="button" id="imagelightbox-close" title="Close"></button>').appendTo('body').on('click touchend', function() {
        $(this).remove();
        instance.quitImageLightbox();
        return false;
      });
    },
    closeButtonOff = function() {
      $('#imagelightbox-close').remove();
    },


    // CAPTION

    captionOn = function() {
      var description = $('a[href="' + $('#imagelightbox').attr('src') + '"] img').attr('alt');
      if ( $.trim(description).length == 0)
      {
         description = "No caption";
      }
      $('<div id="imagelightbox-caption">' + description + '</div>').appendTo('body');
    },


    // NAVIGATION

    navigationOn = function(instance, selector) {
      var images = $(selector);
      if (images.length) {
        var nav = $('<div id="imagelightbox-nav"></div>');
        for (var i = 0; i < images.length; i++)
          nav.append('<button type="button"></button>');

        nav.appendTo('body');
        nav.on('click touchend', function() {
          return false;
        });

        var navItems = nav.find('button');
        navItems.on('click touchend', function() {
            var $this = $(this);
            if (images.eq($this.index()).attr('href') != $('#imagelightbox').attr('src'))
              instance.switchImageLightbox($this.index());

            navItems.removeClass('active');
            navItems.eq($this.index()).addClass('active');

            return false;
          })
          .on('touchend', function() {
            return false;
          });
      }
    },
    navigationUpdate = function(selector) {
      var items = $('#imagelightbox-nav button');
      items.removeClass('active');
      items.eq($(selector).filter('[href="' + $('#imagelightbox').attr('src') + '"]').index(selector)).addClass('active');
    },
    navigationOff = function() {
      $('#imagelightbox-nav').remove();
    },


    // ARROWS

    arrowsOn = function(instance, selector) {
      var $arrows = $('<button type="button" class="imagelightbox-arrow imagelightbox-arrow-left"></button><button type="button" class="imagelightbox-arrow imagelightbox-arrow-right"></button>');

      $arrows.appendTo('body');

      $arrows.on('click touchend', function(e) {
        e.preventDefault();

        var $this = $(this),
          $target = $(selector + '[href="' + $('#imagelightbox').attr('src') + '"]'),
          index = $target.index(selector);

        if ($this.hasClass('imagelightbox-arrow-left')) {
          index = index - 1;
          if (!$(selector).eq(index).length)
            index = $(selector).length;
        } else {
          index = index + 1;
          if (!$(selector).eq(index).length)
            index = 0;
        }

        instance.switchImageLightbox(index);
        return false;
      });
    },
    arrowsOff = function() {
      $('.imagelightbox-arrow').remove();
    };



  var selectorF = 'a[data-imagelightbox="f"]';
  var instanceF = $(selectorF).imageLightbox({
    onStart: function() {
      overlayOn();
      closeButtonOn(instanceF);
      arrowsOn(instanceF, selectorF);
      navigationOn(instanceF, selectorF);
    },
    onEnd: function() {
      overlayOff();
      captionOff();
      closeButtonOff();
      arrowsOff();
      activityIndicatorOff();
      navigationOff();
    },
    onLoadStart: function() {
      captionOff();
      activityIndicatorOn();
    },
    onLoadEnd: function() {
      captionOn();
      activityIndicatorOff();
      $('.imagelightbox-arrow').css('display', 'block');
      navigationUpdate(selectorF);
    }
  });

});
&#13;
html {
  /* killing 300ms touch delay in IE */
  -ms-touch-action: manipulation;
  touch-action: manipulation;
}
a img {
  width: 200px;
  height: 200px;
}
button {
  border: none;
  cursor: pointer;
}
/* IMAGE LIGHTBOX SELECTOR */

#imagelightbox {
  cursor: pointer;
  position: fixed;
  z-index: 10000;
  -ms-touch-action: none;
  touch-action: none;
  -webkit-box-shadow: 0 0 3.125em rgba(0, 0, 0, .75);
  box-shadow: 0 0 3.125em rgba(0, 0, 0, .75);
}
/* ACTIVITY INDICATION */

#imagelightbox-loading,
#imagelightbox-loading div {
  border-radius: 50%;
}
#imagelightbox-loading {
  width: 2.5em;
  height: 2.5em;
  background-color: rgba(0, 0, 0, .5);
  position: fixed;
  z-index: 10003;
  top: 50%;
  left: 50%;
  margin: -1.25em 0 0 -1.25em;
  -webkit-box-shadow: 0 0 2.5em rgba(0, 0, 0, .75);
  box-shadow: 0 0 2.5em rgba(0, 0, 0, .75);
}
#imagelightbox-loading div {
  margin: 25%;
  width: 1.25em;
  height: 1.25em;
  background-color: #fff;
  -webkit-animation: imagelightbox-loading .5s ease infinite;
  animation: imagelightbox-loading .5s ease infinite;
}
@-webkit-keyframes imagelightbox-loading {
  from {
    opacity: .5;
    -webkit-transform: scale(.75);
  }
  50% {
    opacity: 1;
    -webkit-transform: scale(1);
  }
  to {
    opacity: .5;
    -webkit-transform: scale(.75);
  }
}
@keyframes imagelightbox-loading {
  from {
    opacity: .5;
    transform: scale(.75);
  }
  50% {
    opacity: 1;
    transform: scale(1);
  }
  to {
    opacity: .5;
    transform: scale(.75);
  }
}
/* OVERLAY */

#imagelightbox-overlay {
  background-color: rgba(255, 255, 255, .9);
  position: fixed;
  z-index: 9998;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
/* "CLOSE" BUTTON */

#imagelightbox-close {
  width: 2.5em;
  height: 2.5em;
  text-align: left;
  background-color: #666;
  border-radius: 50%;
  position: fixed;
  z-index: 10002;
  top: 2.5em;
  right: 2.5em;
  -webkit-transition: color .3s ease;
  transition: color .3s ease;
}
#imagelightbox-close:hover,
#imagelightbox-close:focus {
  background-color: #111;
}
#imagelightbox-close:before,
#imagelightbox-close:after {
  width: 2px;
  background-color: #fff;
  content: '';
  position: absolute;
  top: 20%;
  bottom: 20%;
  left: 50%;
  margin-left: -1px;
}
#imagelightbox-close:before {
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}
#imagelightbox-close:after {
  -webkit-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  transform: rotate(-45deg);
}
/* CAPTION */

#imagelightbox-caption {
  text-align: center;
  color: #fff;
  background-color: #666;
  position: fixed;
  z-index: 10001;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 0.625em;
}
/* NAVIGATION */

#imagelightbox-nav {
  background-color: rgba(0, 0, 0, .5);
  border-radius: 20px;
  position: fixed;
  z-index: 10001;
  left: 50%;
  bottom: 3.75em;
  padding: 0.313em;
  -webkit-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  transform: translateX(-50%);
}
#imagelightbox-nav button {
  width: 1em;
  height: 1em;
  background-color: transparent;
  border: 1px solid #fff;
  border-radius: 50%;
  display: inline-block;
  margin: 0 0.313em;
}
#imagelightbox-nav button.active {
  background-color: #fff;
}
/* ARROWS */

.imagelightbox-arrow {
  width: 3.75em;
  height: 7.5em;
  background-color: rgba(0, 0, 0, .5);
  vertical-align: middle;
  display: none;
  position: fixed;
  z-index: 10001;
  top: 50%;
  margin-top: -3.75em;
}
.imagelightbox-arrow:hover,
.imagelightbox-arrow:focus {
  background-color: rgba(0, 0, 0, .75);
}
.imagelightbox-arrow:active {
  background-color: #111;
}
.imagelightbox-arrow-left {
  left: 2.5em;
}
.imagelightbox-arrow-right {
  right: 2.5em;
}
.imagelightbox-arrow:before {
  width: 0;
  height: 0;
  border: 1em solid transparent;
  content: '';
  display: inline-block;
  margin-bottom: -0.125em;
}
.imagelightbox-arrow-left:before {
  border-left: none;
  border-right-color: #fff;
  margin-left: -0.313em;
}
.imagelightbox-arrow-right:before {
  border-right: none;
  border-left-color: #fff;
  margin-right: -0.313em;
}
#imagelightbox-loading,
#imagelightbox-overlay,
#imagelightbox-close,
#imagelightbox-caption,
#imagelightbox-nav,
.imagelightbox-arrow {
  -webkit-animation: fade-in .25s linear;
  animation: fade-in .25s linear;
}
@-webkit-keyframes fade-in {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
@keyframes fade-in {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
@media only screen and (max-width: 41.250em) {
  #imagelightbox-close {
    top: 1.25em;
    right: 1.25em;
  }
  .imagelightbox-arrow {
    width: 2.5em;
    height: 3.75em;
    margin-top: -2.75em;
  }
  .imagelightbox-arrow-left {
    left: 1.25em;
  }
  .imagelightbox-arrow-right {
    right: 1.25em;
  }
}
@media only screen and (max-width: 20em) {
  .imagelightbox-arrow-left {
    left: 0;
  }
  .imagelightbox-arrow-right {
    right: 0;
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class='images'>

  <a data-imagelightbox="f" href="https://3.bp.blogspot.com/-w_GzlVRbQfY/VuKOdAE_emI/AAAAAAAAAVw/LRMazf4otRI4RY8Cmu1MjE7C0M9HII51g/s1600/demo1.jpg">
    <img alt='Sample caption' src="https://3.bp.blogspot.com/-w_GzlVRbQfY/VuKOdAE_emI/AAAAAAAAAVw/LRMazf4otRI4RY8Cmu1MjE7C0M9HII51g/s1600/demo1.jpg" />
  </a>

  <a data-imagelightbox="f" href="https://1.bp.blogspot.com/-2s4gNMJNmvM/VuKO344_tgI/AAAAAAAAAWM/36_nKtGTZyQaFJ_EX2jzSm3wub7SA_jGg/s1600/demo2.jpg">
    <img src="https://1.bp.blogspot.com/-2s4gNMJNmvM/VuKO344_tgI/AAAAAAAAAWM/36_nKtGTZyQaFJ_EX2jzSm3wub7SA_jGg/s1600/demo2.jpg" />
  </a>

</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

  

所以,我想添加条件,如果'alt属性是   丢失或空白'然后显示文字'无标题'。

当缺少属性attr()时,方法返回undefined,这就是description.length失败的原因。

您需要将captionOn方法编辑为

captionOn = function() {
      var description = $('a[href="' + $('#imagelightbox').attr('src') + '"] img').attr('alt');
      if ( $.trim(description).length == 0)
      {
         description = "No caption";
      }
      $('<div id="imagelightbox-caption">' + description + '</div>').appendTo('body');
}

答案 1 :(得分:2)

检查属性alt是否存在,因为你可以像这样使用jQuery函数is()

captionOn = function(){
    // Our image
    var img = $('a[href="' + $('#imagelightbox').attr('src') + '"] img');

    // Find if image has the alt attribute 
    if ($(img).is('[alt]'))
    {
        // If it does have. Get the value inside it and store it in the variable description
        var description = $(img).attr('alt');

        // Show the lightbox with value in description
        $('<div id="imagelightbox-caption">' + description + '</div>').appendTo('body');
    }
}

或者,如果您想要description的默认值,例如'No Caption'

captionOn = function(){
    // Our image
    var img = $('a[href="' + $('#imagelightbox').attr('src') + '"] img');

    // Declare a new variable with the default value.
    var description = 'No Caption';

    // Find if image has the alt attribute 
    if ($(img).is('[alt]'))
    {
            // If it does have. 
            // Get the value inside it and store it variable description
            description = $(img).attr('alt');
    }

    // Show the lightbox with the value stored in description
    $('<div id="imagelightbox-caption">' + description + '</div>').appendTo('body');
}