当ajax成功时,如何将classClass添加到具有相同类的兄弟姐妹中

时间:2017-06-12 09:09:05

标签: jquery ajax siblings

我想用ajax创建模板。 当按钮klik它应该从sample.html调用模板时,模板结构更像是var sample,如果它总是显示错误结果,请原谅我。

我想在ajax成功调用之后将类添加到.contentLoad,所以当它成功时,.contentLoad已经在DOM addClass(' hidden')中,除了我从ajax添加的新.contentLoad。

当ajax成功时,是否可以将addClass添加到具有相同类的兄弟中?



$(document).ready(function() {
  $('.klik').on('click', function() {
    $('.contentLoad').addClass('hidden');
    chooseClick();
  });
});


var sample = '<div class="contentLoad" style="display: none;">' +
  '<div class="contImg">' +
  '<img class="imgres" src="https://static.pexels.com/photos/92957/pexels-photo-92957.jpeg" alt="">' +
  '</div>' +
  '</div>';

function chooseClick() {
  $.ajax({
    url: 'sample.html',
    success: function(temp) {
      $('.load').append(temp).waitForImages(function() {
        $('.loader').hide();
        $('.contentLoad').show();
      });
    },
    error: function() {
      $('.load').prepend('<p>cannot found data</p>');
      $('.loader').hide();
    },
    beforeSend: function() {
      $('.loader').show();
    }
  })
}
&#13;
.load {
  position: relative;
  width: 1320px;
  margin: auto;
}

.imgres {
  max-width: 100%;
  height: auto;
}

.contentLoad {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 10;
}

.hidden {
  opacity: 0;
  z-index: 1;
}

.loader {
  display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="klik">show</button>
<p class="loader">Loading</p>
<h3>load image here</h3>
<div class="load">
  <div class="contentLoad">
    <div class="contImg">
      <img class="imgres" src="https://now.uiowa.edu/sites/now.uiowa.edu/files/styles/640_wide/public/11_ui_school_of_music.jpg?itok=mxvtE2Am" alt="">
    </div>
  </div>

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

1 个答案:

答案 0 :(得分:1)

你可以用这个

var sample = '<div id="newSample" class="contentLoad" style="display: none;">' +
  '<div class="contImg">' +
  '<img class="imgres" src="https://static.pexels.com/photos/92957/pexels-photo-92957.jpeg" alt="">' +
  '</div>' +
  '</div>';

$('.contentLoad:not(#nemSample)').addClass("YourClass")