等同于JQuery .each()&的Javascript原生$(这个) [英] Javascript native equivalent to JQuery .each() & $(this)
问题描述
我有以下代码,该代码查看类为.comment
的每个div,并且如果超过100个字符,则将缩短文本.使用JQuery.
I have the following code which looks at each div with class .comment
and shortens the text if more than 100 characters. Using JQuery.
问题是如何转换为本地javascript,我找不到.each()
或$(this)
Question is how to convert to native javascript, I can't find equivalents for .each()
or $(this)
var showChar = 100;
var ellipsestext = "...";
var moretext = "more";
var lesstext = "less";
$('.comment').each(function() {
var content = $(this).html();
if(content.length > showChar) {
var c = content.substr(0, showChar);
var h = content.substr(showChar-1, content.length - showChar);
var html = c + '<span class="moreellipses">' + ellipsestext+ ' </span><span class="morecontent"><span>' + h + '</span></span>';
$(this).html(html);
}
});
这可能吗?
推荐答案
您不会找到与$(this)
等效的本机,因为是 jQuery函数.如果$
函数本身已经存在,则没有任何理由要编写它.
You're not going to find a native equivalent to $(this)
because that is the jQuery function. There wouldn't be any reason to write the $
function if it already existed natively.
对于.each
部分,您可以使用以下任何数组:
As for the .each
part, you can work with any array like this:
var $comments = $('.comment');
comments.forEach(function(comment) { ... });
或使用简单的for
循环:
for (var i = 0, len = $comments.length; i < len; i++) {
var comment = $comments[i];
}
如果要完全删除jQuery,则需要使用document.getElementsByClassName
来获取元素.这将返回一个不具有forEach
函数的HTMLCollection
,因此您需要使用上述的for
循环.
If you want to remove jQuery entirely, you'll need to get your elements using document.getElementsByClassName
. This will return an HTMLCollection
which does not have the forEach
function so you'll need to use a for
loop like above.
还请注意,您将无权使用.html
功能.相反,您可以使用每个节点的.innerHTML
属性访问和修改它.
Also note that you won't have access to the .html
function. Instead, you can access and modify it with the .innerHTML
property of each node.
var comments = document.getElementsByClassName('comment');
for (var i = 0, len = comments.length; i < len; i++) {
var comment = comments[i];
var content = comment.innerHTML;
...
comment.innerHTML = html;
}
更新时间:2019-12-02
如今,使用 document.querySelectorAll
来查询元素,您可以使用 Array.from
,如果您想将NodeList
转换为数组.
Update: 2019-12-02
Nowadays it is more common to use document.querySelectorAll
for querying elements and you can use Array.from
if you would like to convert the NodeList
to an array.
function boldComments() {
const comments = document.querySelectorAll('.comment');
comments.forEach(comment => {
comment.innerHTML = '<b>' + comment.innerHTML + '</b>';
})
}
document.querySelector('button').addEventListener('click', boldComments);
<ul>
<li class="comment">Comment A</li>
<li class="comment">Comment B</li>
<li class="comment">Comment C</li>
<li class="comment">Comment D</li>
</ul>
<button>Bold comments</button>
这篇关于等同于JQuery .each()&的Javascript原生$(这个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!