简体   繁体   English

您如何使用jQuery来系统地更改Twitter.com上所有头像的src属性?

[英]How can you use jQuery to change all the avatar images' src attribute on Twitter.com systematically?

TL;DR: For all "img.avatar" on Twitter.com, I want to replace "_normal.png" for ".png" in the src attribute. TL; DR:对于Twitter.com上的所有“ img.avatar”,我想将src属性中的“ .png”替换为“ _normal.png”。 See the code and the error I get below. 请参阅下面的代码和错误。

Context: I'm in the process of learning JavaScript and jQuery. 上下文:我正在学习JavaScript和jQuery。 So, I like to write small scripts to automate things as practice. 因此,我喜欢写一些小的脚本来使事情自动化。

Problem: So, I have a Retina MacBook Pro and the 48px avatars on twitter.com look horrible (I know, #firstworldproblem, but bear with me). 问题:因此,我有一个Retina MacBook Pro,twitter.com上的48px头像看上去很可怕(我知道,#firstworldproblem,但请耐心等待)。 I noticed that the difference between the URL of the small 48px avatars and the large version is that the former ends with "_normal.png", while the latter simply ends with ".png". 我注意到,小的48px头像和大版本的URL之间的区别在于,前者以“ _normal.png”结尾,而后者以“ .png”结尾。 Example: 例:

48px thumbnail: 
https://blablabla.com/7f11851408ac5220e361a22f1583e0db_normal.png 

Large version: 
https://blablabla.com/7f11851408ac5220e361a22f1583e0db.png

This being said, I thought of applying my jQuery knowledge and systematically removing the "_normal" at the end of the src attribute of every avatar image, which can be identified with the "avatar" class. 话虽这么说,我想到了要运用我的jQuery知识,并系统地删除每个头像图像src属性末尾的“ _normal”,可以用“ avatar”类来识别。 What's the point? 重点是什么? Just so that it lo Here's what I tried: 就是这样,这是我尝试过的:

jQuery("img.avatar").each( function(){
    $(this).attr("src", $(this).attr("src").replace("_normal.png", ".png"))
});

And here's the error I get in the Console: 这是我在控制台中遇到的错误:

TypeError: Cannot call method 'replace' of undefined

What am I doing wrong? 我究竟做错了什么? Why is $(this).attr("src") undefined, from what I understand of the error? 根据我对错误的了解,为什么未定义$(this).attr("src")

PS I'm relatively new to Stack Exchange, so give me a heads-up if I'm transgressing any conventions. PS:对于Stack Exchange来说,我是相对较新的人,因此,如果我违反任何约定,请多加注意。

There exist some img elements without an src attribute in them. 存在一些没有src属性的img元素。 This would be what's causing a problem. 这就是造成问题的原因。 Try adding a condition before changing the attribute, like so: 尝试在更改属性之前添加条件,如下所示:

jQuery("img.avatar").each( function(){
    if($(this).attr('src'))
        $(this).attr("src", $(this).attr("src").replace("_normal.png", ".png"))
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM