1

通常は修正できないテンプレート化されたコードを「ハック」するための小さなコード スニペットがあります。

<script>
jQuery( document ).ready(function() {
    jQuery(".avatar").each(function() {
        var text = jQuery(this).attr("src");
        text = text.replace("-64x64.jpg", ".jpg");
        text = text.replace("-80x80.jpg", ".jpg");
        text = text.replace("-32x32.jpg", ".jpg");
        text = text.replace("-28x28.jpg", ".jpg");
        text = text.replace("-16x16.jpg", ".jpg");
        text = text.replace("-128x128.jpg", ".jpg");
        jQuery(this).attr("src", text);
    });
});
</script>

上記のスクリプトをブラウザで実行すると、コンソールに次のエラーが表示されます。

TypeError: text is undefined
text = text.replace("-64x64.jpg", ".jpg");

頭を悩ませていますが、何も思いつきません。var text; を使用してみました。スクリプトの開始時にそれを試して定義し、何かと競合する場合に備えて別の変数名を使用しようとしましたが、どちらも何もしませんでした....

4

1 に答える 1

7

これは、class を持つ要素の少なくとも 1 つに属性avatarがないことを意味しsrcます。問題の要素に属性がまったくない場合にattr返されます。undefined

( )内にガードを入れることができますif (text)。例を次に示します。また、使用する理由がないことに注意してくださいjQuery(this).attr("src")。ちょうど使用this.src

jQuery( document ).ready(function() {
    jQuery(".avatar").each(function() {
        if (this.src) {
          this.src = this.src.replace("-64x64.jpg", ".jpg")
                             .replace("-80x80.jpg", ".jpg")
                             .replace("-32x32.jpg", ".jpg")
                             .replace("-28x28.jpg", ".jpg")
                             .replace("-16x16.jpg", ".jpg")
                             .replace("-128x128.jpg", ".jpg");
        }
    });
});

正規表現を使用して、そのコードをもう少し堅牢にすることもできます。

jQuery( document ).ready(function() {
    jQuery(".avatar").each(function() {
        if (this.src) {
          this.src = this.src.replace(/-(\d+x\d+)\.jpg$/, ".jpg");
        }
    });
});

それぞれの場合の数字が何であるかについて特定することなく、それは に置き換え-DIGITSxDIGITS.jpgられます。は「任意の数字」を意味し、その後は「1 つ以上」を意味します。.jpg\d+

于 2013-09-06T09:49:52.270 に答える