所以我有一段代码可以在列表中显示奖牌 (img),我的目标是一旦显示 5 里,之后再切断。 (如果可能的话,显示三个省略号 ...
以将用户重定向到他们可以看到所有这些奖章的地方。)感谢所有帮助!
<div id="medals">
<h3 style="text-decoration:underline;">User medals:</h3>
<ul>
<script>
document.getElementById('medals').getElementsByTagName('li').length >= 5 { } // my first guess at starting something like my question off?
</script>
<li>
<img src="images/medals/startup.png" title="<?php echo $profile_data['display_name']; ?> created a profile!" alt="a medal should be here?">
</li> // a medal that all users get
<?php echo base64_decode($profile_data['medals'] // this code displays all medal <li>'s from MySql database); ?>
</ul>
</div>
最佳答案
您可以使用几个带偏移量的 strpos() 来获取最后一个 </li>
的位置.
然后使用该位置获取你想要的子串。
<div id="medals">
<h3 style="text-decoration:underline;">User medals:</h3>
<ul>
<li>
<img src="images/medals/startup.png" title="<?php echo $profile_data['display_name']; ?> created a profile!" alt="a medal should be here?">
</li> // a medal that all users get
<?php $medalslist = base64_decode($profile_data['medals']; // this code displays all medal <li>'s from MySql database);
$pos = strpos($medalslist, '</li>', strpos($medalslist, '</li>', strpos($medalslist, '</li>', strpos($medalslist, '</li>', strpos($medalslist, '</li>')+5)+5)+5)+5);
echo substr($medalslist, 0, $pos+5); // get position of last </li>
echo '<li><a href="/USERNAME/MEDALS">...</a></li>';
?>
</ul>
</div>
当然,您不必使用 php 来回显链接到奖牌页面的最后一个 li-Element。但我认为您可能会使用 php 来获取可能是 url 一部分的用户名,所以我这样说。
如果您希望能够轻松更改显示的奖牌数量,您可以使用 for 循环:
<div id="medals">
<h3 style="text-decoration:underline;">User medals:</h3>
<ul>
<li>
<img src="images/medals/startup.png" title="<?php echo $profile_data['display_name']; ?> created a profile!" alt="a medal should be here?">
</li> // a medal that all users get
<?php $medalslist = base64_decode($profile_data['medals']; // this code displays all medal <li>'s from MySql database);
$pos = 0; // set offset to zero
for($i=0;$i<5;$i++) { // 5 is the number of medals to display
$pos = strpos($medalslist, '</li>', $pos+5); // set offset to right after where the last "</li>" was found - +5 because "</li>" has five characters
};
echo substr($medalslist, 0, ($pos > 0 ? $pos+5 : $pos)); // get position of last </li> you want to display
echo '<li><a href="/USERNAME/MEDALS">...</a></li>';
?>
</ul>
</div>
关于javascript - 5 里后不再显示并放置 `...`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21997592/