我试图访问DOM中的某个区域,但我似乎无法用jquery来定位它。
HTML看起来像:
<h4>stuff here</h4>
<div class="answerDiv">
<div class="ExternalClass">
<p>
Need to expand or show this.
</p>
</div>
</div>
<h4>more stuff here</h4>
<div class="answerDiv">
<div class="ExternalClass">
<p>
Need to expand or show this.
</p>
</div>
</div>
我试图定位并扩展说“&#34;需要展开或展示这一点的区域。&#34;
我尝试了大量不同的jQuery选择器:
$(this).toggleClass('expand').nextUntil('h4').slideToggle();
$(this).next().next().slideToggle();
$(this).next(".answerDiv").show();
onlcick方法:
$('h4').click(function () {
$(this).next(".answerDiv").show();
})
我默认使用CSS隐藏.answerDiv类。
完整代码:
<script src="/mapres/jquery.min.js"></script>
<link rel='stylesheet' href='~/css/faq.css' />
<script>
$(document).ready(function () {
populateFAQ();
$(".answerDiv").hide();
toggleContentHeaders();
});
function toggleContentHeaders() {
$('h4').click(function () {
$(this).next(".answerDiv").show();
});
}
function populateFAQ() {
$.ajax({
url: "/_api/web/lists/getbytitle('FAQ')/items?$orderby=ID desc",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
$.each(data.d.results, function(i, item){
$("#faqDiv").append(
"<h4>" + " " + this.Title + "</h4>" +
"<div class='answerDiv'>" + this.Answer + "</div>"
);
});
},
error: function (data) {
console.log(data);
}
});
}
</script>
<body style="background-color:#e3e1e2;">
<div id="faqDiv">
</body>
已更新
我能够通过在ajax函数中嵌套函数而不是文档就绪来解决这个问题
function populateFAQ() {
$.ajax({
url: "/_api/web/lists/getbytitle('FAQ')/items?$orderby=ID desc",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
$.each(data.d.results, function(i, item){
$("#faqDiv").append(
"<h4>" + " " + this.Title + "</h4>" +
"<div class='answerDiv'>" + this.Answer + "</div>"
);
});
$(".answerDiv").hide(); //hidden here
toggleContentHeaders() //added function here
},
error: function (data) {
console.log(data);
}
});
}
</script>