gpt4 book ai didi

javascript - 使用 jQuery 在 div 中隐藏内联文本

转载 作者:太空宇宙 更新时间:2023-11-04 15:55:09 25 4
gpt4 key购买 nike

如何在 .test 类的 div 中隐藏 inline 文本而不隐藏 h1 元素?这是我在大型 Web 应用程序中遇到的问题的简化示例。

其他一些准则是我不能将文本包装在 span 标记中,我想将所有内容保留在 div 中,这样我就不能简单地删除并添加回我想要的所有内容。

$(document).ready(function() {});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<h1>Hello World</h1>
"This is text"
</div>

最佳答案

您需要将文本包裹在另一个元素中,例如 span。

<div class="test">
<h1>Hello World</h1>
<span class="my-text">"This is text"</span>
</div>

还有你的js:

$(document).ready(function() {
$('.my-text').hide();
});

如果由于某种原因您无法换行(正如您在评论中提到的),您可以使用另一种简单的解决方案:

<div class="test">
<h1>Hello World</h1>
This is text
</div>

和js:

$(document).ready(function() {
var h1elem = $('h1'); //cache element which should not be removed
$('.test').empty(); //clear container .test
$('.test').append(h1elem); // append cached element back
});

这是 plunker为你。 (为更好的可视化添加了 2 秒超时)。

关于javascript - 使用 jQuery 在 div 中隐藏内联文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46455145/

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