gpt4 book ai didi

javascript - 无法剪切太长的标题

转载 作者:行者123 更新时间:2023-11-30 12:19:47 25 4
gpt4 key购买 nike

我有一段 javascript 应该检查我网站上所有标题的长度,如果它们太短则将它们剪掉,但是这不会发生。为什么?

var titles = document.getElementsByClassName("newsTitle");
for (i=0; i < titles.length; i++) {
if (titles[i].length > 14) {
var oldTitle = titles[i].value;
var newTitle = oldTitle.substring(0,10) + "...";
titles[i].innerHTML = newTitle;
}
}

body 的一切

<div id="header">
<h1 id="headerTitle">WIP</h1>
<ul id="headerList">
<li class="headerListButton"><a href="http://mastermeredith.com" class="headerListText">Home</a></li>
<li class="headerListButton"><a href="about.html" class="headerListText">About</a></li>
<li class="headerListButton"><a href="archives.html" class="headerListText">Archives</a></li>
</ul>
</div>
<div id="newsHolder">
<!--News pieces go here-->
<?php
$newsPieces = scandir("posts", 1);
for ($i = 0; $i < count($newsPieces) and $i < 12; $i++) {
if ($newsPieces[$i] != "." and $newsPieces[$i] != "..") {
$titlefile = fopen("posts/" . $newsPieces[$i] . "/title.txt", "r");
$textfile = fopen("posts/" . $newsPieces[$i] . "/text.txt", "r")
$fullElement = "<div class='newsPiece'><div class='newsImageHolder'><img class='newsImage' src='posts/" . $newsPieces[$i] . "/image.jpg'></div><div class='newsContent'><h1 class='newsTitle'>" . fread($titlefile, filesize("posts/" . $newsPieces[$i] . "/title.txt")) . "</h1><p class='newsText'>" . fread($textfile, filesize("posts/" . $newsPieces[$i] . "/text.txt")) . "</p><a class='newsLink' href='post?post=" . urlencode($newsPieces[$i]) . "'>Continue Reading</a></div></div>";
echo $fullElement;
fclose($titlefile);
fclose($textfile);
}
}
?>
<script type="text/javascript">
var titles = document.getElementsByClassName("newsTitle");
for (i=0; i < titles.length; i++) {
if (titles[i].length > 14) {
var oldTitle = titles[i].value;
var newTitle = oldTitle.substring(0,10) + "...";
titles[i].innerHTML = newTitle;
}
}
</script>
</div>

最佳答案

您需要使用 .innerHTML 而不是 titles[i].value;,

var oldTitle = titles[i].innerHTML;

因为据我了解标题不是输入,你还需要检查标题长度

var titles = document.getElementsByClassName("newsTitle"),
title;

for (var i = 0, len = titles.length; i < len; i++) {
title = titles[i].innerHTML;

if (title.length > 14) {
titles[i].innerHTML = title.substring(0,10) + "...";
}
}
<h1 class="newsTitle">Test title</h1>
<h1 class="newsTitle">Test title Test title Test title</h1>
<h1 class="newsTitle">Test title Test title Test title</h1>
<h1 class="newsTitle">Test title Test title Test title Test title</h1>

关于javascript - 无法剪切太长的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31468514/

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