尝试在纯JavaScript中创建一个标题长度限制器

huangapple go评论71阅读模式
英文:

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

&lt;div class=&quot;limiter&quot;&gt;
Pandemic deaths are spiraling 
out of control since the 
opening of the country 
and now we test the limiter
&lt;/div&gt;

Here is the JavaScript

document.querySelector(&quot;.limiter&quot;).each(function () {
  var a = 60;
  var b = document.querySelector(this).text();
  if (b.length &gt; a) {
    document.querySelector(this).text(b.substring(0, a + 1) + &quot; ...&quot;);
  } else {
    document.querySelector(this).text(b);
  }
});

Any idea why it does not work ?

答案1

得分: 2

看起来你正在从jQuery转向原生JavaScript。你会注意到代码不可直接迁移。代码看起来_相似_,但语法不同。

更新你的代码:

  1. 要获取类似数组的节点列表,你需要使用 querySelectorAll

  2. each 应该变成 forEach。请注意,还有其他一些方法可以迭代节点列表,但forEach 是你用例最接近的匹配项。它回调的第一个参数是当前迭代的元素。

  3. JavaScript没有text()函数。你需要直接获取/设置 textContent 属性。(或根据你的需要使用 innerText - 你可以在这里看到两者之间的区别)。

  4. 你只需要一个条件 - 当文本长度超过你设定的限制时,才改变文本。在这个示例中,我使用了 slice模板字符串来创建新的截断字符串。

  5. 现在最好放弃使用 var,改用 constlet 来声明变量。

// 设置限制
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:

  1. To pick up an array-like list of nodes you'll need to use querySelectorAll.

  2. each should become forEach. Note there are a few other methods for iterating over the node list but forEach is the closest match for your use-case. The first argument in its callback is the current iterated element.

  3. JavaScript doesn't have a text() function. You need to get/set the textContent property directly. (Or innerText depending on your needs - here you can see the differences between the two).

  4. 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.

  5. These days its better to move on from var and use const or let 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 &quot;limiter&quot; class
// The callback&#39;s first argument &quot;el&quot; is the current
// iterated element
document.querySelectorAll(&#39;.limiter&#39;).forEach(el =&gt; {

  // For convenience assign the text content of the current
  // iterated element to a variable called &quot;text&quot;,
  // and trim the beginning/end whitespace it
  const text = el.textContent.trim();

  // If the text length is greater than the limit
  // set the element&#39;s text content to the truncated content
  if (text.length &gt; limit) {
    el.textContent = `${text.slice(0, limit + 1)}...`;
  }
});

<!-- language: lang-css -->

body &gt; * ~ * { margin-top: 0.5rem; }

<!-- language: lang-html -->

&lt;div class=&quot;limiter&quot;&gt;
  Pandemic deaths are spiraling out of control since the opening of the country and now we test the limiter
&lt;/div&gt;
&lt;div class=&quot;limiter&quot;&gt;
  Lions and Tigers and Bears, Oh My!
&lt;/div&gt;

<!-- 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(&quot;.limiter&quot;);
limiters.forEach(function (element) {
  const a = 60;
  let b = element.textContent;
  if (b.length &gt; a) {
    element.textContent = (b.substring(0, a + 1) + &quot; ...&quot;);
  }
  console.log(b, element.textContent);
});
*/

/* another way */ 
const limiters = document.querySelectorAll(&quot;.limiter&quot;);
for(const el of limiters) {
  const a = 60;
  if (el.textContent.length &gt; a) {
    el.textContent = (el.textContent.substring(0, a + 1) + &quot; ...&quot;);
  }
}

<!-- language: lang-html -->

&lt;div class=&quot;limiter&quot;&gt;
Pandemic deaths are spiraling 
out of control since the 
opening of the country 
and now we test the limiter
&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月10日 20:50:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76653923.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定