[英]How do I get a jQuery function to work with specific elements when they have the same class names?
I have sections (divs) with text in it, but when the text is too long I made it so the text "fades" (with css) and displays a "show more" button, which shows the full text for that specific div when clicked. 我在其中包含文本的部分(divs),但是当文本太长时,我将其设置为文本“ fades”(带有CSS)并显示“显示更多”按钮,该按钮会在该特定div时显示全文点击。 The problem is that it only works for the first div, and I believe it's because they all have the same class and id name.
问题在于它仅适用于第一个div,我相信这是因为它们都具有相同的类和id名称。 What's the best way to get around that?
解决这个问题的最佳方法是什么? Here's my code:
这是我的代码:
HTML: HTML:
<div id="fade-container">
<div id="fade-content">
<p>
Long text goes here...
<div class="fade-anchor"><span class="btn-primary round-xl small btn-shadow">Show more</span></div>
</p>
</div>
</div>
Script: 脚本:
<script>
$('.fade-anchor').click(function(e){
e.preventDefault();
$('#fade-content').css('max-height','none');
$('.fade-anchor').remove();
});
</script>
By the way, info is being fetched from the database in a php while loop. 顺便说一下,信息是通过php while循环从数据库中获取的。
When the user clicks on .fade-anchor
you can use this
to get the element currently selected, you should also use classes instead of ids for multiple elements, like so: 当用户单击
.fade-anchor
,可以使用this
来获取当前选定的元素,还应该对多个元素使用类而不是id,例如:
$('.fade-anchor').click(function(e){
e.preventDefault();
$(this).parent('.fade-content').css('max-height','none');
$(this).hide(); // Maybe you should hide instead of removing, in case you want to add a toggle effect later on.
});
You can also check out this jsFiddle with the working version. 您也可以在工作版本中检出此jsFiddle 。
Hope it helps. 希望能帮助到你。
You can achieve it by e.currentTarget
$('.fade-anchor').click(function(e){
e.preventDefault();
$(e.currentTarget).css('max-height','none');
$('.fade-anchor').remove();});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.