我有3个div
块。基于从我的AJAX请求获得的响应,我想显示或隐藏特定块。假设我已经得到了JSON格式的响应,如下所示:
var response = [{
"class":[
"firstBlock",
"secondBlock"
]
}]
<div class="mianBlock">
<div class="firstBlock">
div content goes here
</div>
<div class="secondBlock">
div content goes here
</div>
<div class="thirdBlock">
div content goes here
</div>
</div>
使用jQuery,如何隐藏2个块?
答案 0 :(得分:5)
您可以访问JSON以从返回的类名构建选择器。试试这个:
var selector = '.' + response[0].class.join(', .');
$(selector).hide();
var response = [{
"class": [
"firstBlock",
"secondBlock"
]
}]
var selector = '.' + response[0].class.join(', .');
$(selector).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mianBlock">
<div class="firstBlock">
div content goes here - firstBlock
</div>
<div class="secondBlock">
div content goes here - secondBlock
</div>
<div class="thirdBlock">
div content goes here - thirdBlock
</div>
</div>
答案 1 :(得分:0)
JS
var response = [
{
"class":[
"firstBlock",
"secondBlock"
]
}
]
$(".mianBlock >div").show();
$.each(response, function(i,items) {
$.each(items.class, function(j,value) {
var element=".mianBlock ."+value;
console.log(element);
$(element).hide();
});
});
HTML
<div class="mianBlock">
<div class="firstBlock">
div content goes here - firstBlock
</div>
<div class="secondBlock">
div content goes here - secondBlock
</div>
<div class="thirdBlock">
div content goes here - thirdBlock
</div>
</div>