gpt4 book ai didi

javascript - 在父DIV下按类查找DIV

转载 作者:太空宇宙 更新时间:2023-11-03 22:36:05 25 4
gpt4 key购买 nike

我有几个 DIV 元素嵌套在一个父容器下。当用户点击其中一个 cp-anchor 时,我想修改另一个 cp-content 上的 CSS。我已经尝试了在 Stack Overflow 上找到的几十种方法,但出于某种原因,它似乎没有按预期工作。谁能帮我指出正确的方向?

这是一个JSFiddle我正在使用的示例。

    <script type="text/javascript">

$( document ).ready(function()
{
$('.cp-anchor').click(function(e)
{
e.preventDefault();

$(this).parent().find('cp-content').css('max-height','none');
$(this).remove();
});
});

</script>

<div class="cp-container">
<div class="cp-content">
<table id="tablepress-4">
</table>
</div>
<div class="cp-anchor"><span class="cp-anchor-text">Show Full Contents</span></div>
</div>

最佳答案

您需要一个 . 来表示类别选择。

//                     v
$(this).parent().find('.cp-content').css('max-height','none');

$(document).ready(function() {
$('.cp-anchor').click(function(e) {
e.preventDefault();

$(this).parent().find('.cp-content').css('max-height', 'none');
$(this).remove();
});
});
.cp-content {
max-height: 0;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cp-container">
<div class="cp-content">
CP CONTENT
</div>
<div class="cp-anchor"><span class="cp-anchor-text">Show Full Contents</span></div>
</div>


这是一个普通的 JS 版本:

document.addEventListener("DOMContentLoaded", function() {
document.querySelectorAll('.cp-anchor')
.forEach(el => el.addEventListener("click", showContent));

function showContent(e) {
e.preventDefault();

this.parentNode.querySelector('.cp-content').style.maxHeight = 'none';
this.remove();
}
});
.cp-content {
max-height: 0;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cp-container">
<div class="cp-content">
CP CONTENT
</div>
<div class="cp-anchor"><span class="cp-anchor-text">Show Full Contents</span></div>
</div>

关于javascript - 在父DIV下按类查找DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46433057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com