我正在尝试使用从数据库加载的数据来创建“Read more / Read less”功能。
我的jQuery函数非常适用于我的HTML页面中已存在的数据,但不适用于从数据库加载的数据。
我的代码:
<body>
<div class="slider ">
<?php
//connexion to data base config
while ( /* condition */)
{
//other config
?>
<div class="w-slide news-slide">
<p class="article-text-style">
<?php
news_affiche_fiche($newsId);
?>
</p>
</div>
<?php
}
?>
<div class="w-slide news-slide">
<!-- JQUERY function work with this parag but not with other loaded from DB -->
<p class="article-text-style">Storea owner Steve Witmere previously arrested for blackmarket bazooka trading. Confesses to involvement in Russian mafia.</p>
</div>
</div>
</body>
<script >
$(window).bind("load",function() {
// Configure/customize these variables.
var showChar = 100; // How many characters are shown by default
var ellipsestext = "...";
var moretext = "Show more >";
var lesstext = "Show less";
$('.article-text-style').each(function() {
var content = $(this).html();
if(content.length > showChar) {
var c = content.substr(0, showChar);
var h = content.substr(showChar, content.length - showChar);
var html = c + '<span class="moreellipses">' + ellipsestext+ ' </span><span class="morecontent"><span>' + h + '</span> <a href="" class="morelink">' + moretext + '</a></span>';
$(this).html(html);
}
});
$(".morelink").click(function(){
if($(this).hasClass("less")) {
$(this).removeClass("less");
$(this).html(moretext);
} else {
$(this).addClass("less");
$(this).html(lesstext);
}
$(this).parent().prev().toggle();
$(this).prev().toggle();
return false;
});
});
</script>
CSS文件:
.morecontent span {
display: none;
}
.morelink {
display: block;
}
答案 0 :(得分:0)
确保您的news_affiche_fiche($newsId);
没有在内容周围打印其他标签。鉴于您的javascript,如果内容直接位于<p class="article-text-style">
,那么它将起作用,但如果是这样的话,则不会:
<p class="article-text-style">
<p class="another-p">text here</p>
</p>