我有一个有两个类的变量。我希望在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>
答案 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)
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;
答案 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~