Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

以下两段jq代码要是用js来写,怎么写的呀?

最近不是都在去掉jq吗。我这两段jq代码想转原生js。求大佬。

获取图片alt信息

// 获取图片alt信息
$(".entry-content p img,.lonesome-img a img").each(function(){ 
    $("<figcaption class='image_title'></figcaption>").insertAfter(this); 
    var thisImage = $(this).parents('.entry-content p,.lonesome-img a').find('img'); 
    var title = thisImage.attr('alt'); 
    $(this).siblings('.image_title').html(title); 
});

给不是图片链接的a标签里加rel

// 给不是图片链接的a标签里加rel
const regx = /.(jpe?g|png)(?=?|$)/i; // 正则表达式
$('.entry-content').find('a').each(function(){
    const href = $(this).attr('href');
    const isImg = regx.test(href); // 正则表达式与目标字符串是否匹配
    if (!isImg) {
        $(this).attr('rel', 'external');
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

document.querySelectorAll(".entry-content p img,.lonesome-img a img") 就是所有img

Array.form(document.querySelector(".entry-content p img,.lonesome-img a img")) 就是转换成数组,然后就可以快乐的 forEach 了

你之前代码写的感觉也不是很对呀。

去掉 jquery 也不是这么个去法呀,明明有 jquery 能省事


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...