html()之前的removeClass

时间:2017-04-05 14:26:59

标签: javascript jquery html

我有一个有两个类的变量。我希望在small将div推送到html()之前删除DOM类。

截至目前,div正在使用small类进行渲染。我希望将其删除。

我已尝试更改removeClass的顺序,将其放在html()之前,但这不起作用。

$('#review').removeClass('small').html(prev);

有谁知道我该怎么做?

var prev = "<div class='big small'>Hello</div>";
$('#review').html(prev).removeClass('small');
.big {
  color: red;
  font-size: 2rem;
}
.small {
  color: blue;
  font-size: 1.1rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="review"></div>

更新

为了简单起见,我试图让我的问题变得非常简单,但事实证明,我在实际代码中使用的数组使这个问题变得更加复杂。

$('body').on('change', '.option-check', function() {
  var calSelectionImg = [];
  $('.calendar-check:checked').each(function() {
    calSelectionImg.push($(this).data('calendar-img'));
  });
  $('#pg-img-review').html(calSelectionImg);
});
.cal-selected-img {
  color: red;
  font-size: 2rem;
}

.small {
  color: blue;
  font-size: 1.1rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" class="option-check" data-cal-choice="<div class='cal-selected-img small'>Hello</div>">

<input type="checkbox" class="option-check" data-cal-choice="<div class='cal-selected-img small'>Goodbye</div>">

<div id="pg-img-review" class="margin15"></div>

4 个答案:

答案 0 :(得分:2)

您正在修改#review,而不是新代码。所以,我添加了appendTo。这是一个微小的重组,但它解决了最小的复杂问题。

var prev = "<div class='big small'>Hello</div>";
$(prev).removeClass('small').appendTo("#review");
.big {
  color: red;
  font-size: 2rem;
}
.small {
  color: blue;
  font-size: 1.1rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="review"></div>

答案 1 :(得分:1)

在您给出的示例中,prev中的HTML只是一个字符串。您需要先将其解析为DOM对象,然后才能在其上调用.removeClass()等函数。

jQuery提供了许多用于解析HTML元素的选项,但作为jQuery支持者的普通JS,我经常赞成this特定的方法:

var tempDiv = document.createElement('div');
tempDiv.innerHtml = "<p class='small'>The string of HTML</p>";
var parsedElement = tempDiv.firstChild;

然后我可以调用jQuery方法parsedElement.removeClass("small")或Vanilla JS parsedElement.classList.remove("small")来成功删除该类。

答案 2 :(得分:0)

&#13;
&#13;
var prev = "<div class='big small'>Hello</div>";
$('#review').html(prev).find('.small').removeClass('small');
&#13;
.big {
  color: red;
  font-size: 2rem;
}
.small {
  color: blue;
  font-size: 1.1rem;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="review"></div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

你可能需要这个:

var prev = "<div class='big small'>Hello</div>";
$('#review').html(prev);
$(".big").removeClass('small');

首先添加您的DIV,然后删除您以后不需要的课程。

别担心

$(".big").removeClass('small');

会导致任何问题。如果没有CLASS [small],DOM将忽略js。

那是全部.O(∩_∩)O~