英文:
Trying to create a title length-limiter in pure JavaScript
问题
我想在标题中使用纯JavaScript设置最大长度为60个字符,但它似乎无法正常工作。
这是HTML部分:
<div class="limiter">
大流行的死亡人数自国家开放以来一直在失控增加,现在我们测试这个限制器
</div>
这是JavaScript部分:
document.querySelector(".limiter").each(function () {
var a = 60;
var b = document.querySelector(this).text();
if (b.length > a) {
document.querySelector(this).text(b.substring(0, a + 1) + " ...");
} else {
document.querySelector(this).text(b);
}
});
有什么原因导致它无法正常工作吗?
英文:
I want to set a Max length of 60 characters in titles, using pure JavaScript. But it does not want to work.
Here is the html
<div class="limiter">
Pandemic deaths are spiraling
out of control since the
opening of the country
and now we test the limiter
</div>
Here is the JavaScript
document.querySelector(".limiter").each(function () {
var a = 60;
var b = document.querySelector(this).text();
if (b.length > a) {
document.querySelector(this).text(b.substring(0, a + 1) + " ...");
} else {
document.querySelector(this).text(b);
}
});
Any idea why it does not work ?
答案1
得分: 2
看起来你正在从jQuery转向原生JavaScript。你会注意到代码不可直接迁移。代码看起来_相似_,但语法不同。
更新你的代码:
-
要获取类似数组的节点列表,你需要使用
querySelectorAll
。 -
each
应该变成forEach
。请注意,还有其他一些方法可以迭代节点列表,但forEach
是你用例最接近的匹配项。它回调的第一个参数是当前迭代的元素。 -
JavaScript没有
text()
函数。你需要直接获取/设置textContent
属性。(或根据你的需要使用innerText
- 你可以在这里看到两者之间的区别)。 -
你只需要一个条件 - 当文本长度超过你设定的限制时,才改变文本。在这个示例中,我使用了
slice
和模板字符串来创建新的截断字符串。
// 设置限制
const limit = 60;
// 获取所有具有 "limiter" 类的元素
// 回调函数的第一个参数 "el" 是当前迭代的元素
document.querySelectorAll('.limiter').forEach(el => {
// 为了方便,将当前迭代元素的文本内容赋值给名为 "text" 的变量,
// 并修剪开头/结尾的空格
const text = el.textContent.trim();
// 如果文本长度大于限制
// 设置元素的文本内容为截断后的内容
if (text.length > limit) {
el.textContent = `${text.slice(0, limit + 1)}...`;
}
});
body > * ~ * { margin-top: 0.5rem; }
<div class="limiter">
自国家开放以来,大流行的死亡人数正在失控增加,现在我们测试限制器
</div>
<div class="limiter">
狮子和老虎和熊,哦,天哪!
</div>
英文:
It looks like you're moving from jQuery to vanilla JavaScript. You'll notice that the code isn't transferable. The code looks similar but the syntax is different.
Updating your code:
-
To pick up an array-like list of nodes you'll need to use
querySelectorAll
. -
each
should becomeforEach
. Note there are a few other methods for iterating over the node list butforEach
is the closest match for your use-case. The first argument in its callback is the current iterated element. -
JavaScript doesn't have a
text()
function. You need to get/set thetextContent
property directly. (OrinnerText
depending on your needs - here you can see the differences between the two). -
You need one condition - to change the text if its length exceeds the limit you've imposed. In this example I've used
slice
and a template string to create the new truncated string. -
These days its better to move on from
var
and useconst
orlet
to declare your variables.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// Set the limit
const limit = 60;
// Grab all the elements with a "limiter" class
// The callback's first argument "el" is the current
// iterated element
document.querySelectorAll('.limiter').forEach(el => {
// For convenience assign the text content of the current
// iterated element to a variable called "text",
// and trim the beginning/end whitespace it
const text = el.textContent.trim();
// If the text length is greater than the limit
// set the element's text content to the truncated content
if (text.length > limit) {
el.textContent = `${text.slice(0, limit + 1)}...`;
}
});
<!-- language: lang-css -->
body > * ~ * { margin-top: 0.5rem; }
<!-- language: lang-html -->
<div class="limiter">
Pandemic deaths are spiraling out of control since the opening of the country and now we test the limiter
</div>
<div class="limiter">
Lions and Tigers and Bears, Oh My!
</div>
<!-- end snippet -->
答案2
得分: 1
请参考此处以了解更多信息 Ref: stackoverflow.com/q/9329446/125981
/* 一种方法 */
/*
const limiters = document.querySelectorAll(".limiter");
limiters.forEach(function (element) {
const a = 60;
let b = element.textContent;
if (b.length > a) {
element.textContent = (b.substring(0, a + 1) + " ...");
}
console.log(b, element.textContent);
});
*/
/* 另一种方法 */
const limiters = document.querySelectorAll(".limiter");
for(const el of limiters) {
const a = 60;
if (el.textContent.length > a) {
el.textContent = (el.textContent.substring(0, a + 1) + " ...");
}
}
<div class="limiter">
Pandemic deaths are spiraling
out of control since the
opening of the country
and now we test the limiter
</div>
英文:
Refer here to learn more Ref: stackoverflow.com/q/9329446/125981
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
/* one way */
/*
const limiters = document.querySelectorAll(".limiter");
limiters.forEach(function (element) {
const a = 60;
let b = element.textContent;
if (b.length > a) {
element.textContent = (b.substring(0, a + 1) + " ...");
}
console.log(b, element.textContent);
});
*/
/* another way */
const limiters = document.querySelectorAll(".limiter");
for(const el of limiters) {
const a = 60;
if (el.textContent.length > a) {
el.textContent = (el.textContent.substring(0, a + 1) + " ...");
}
}
<!-- language: lang-html -->
<div class="limiter">
Pandemic deaths are spiraling
out of control since the
opening of the country
and now we test the limiter
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论