有沒有辦法使用 jQuery 來更改影像源 URL 的一部分?
我正在處理一個頁面,該頁面包含許多以編程方式生成的影像元素(但我無法訪問生成它們的源代碼)。他們都共享同一個班級。
假設我有以下 HTML:
<img src="https://cdn.example.com/pictures/01.jpg" class="photo">
<img src="https://cdn.example.com/pictures/02.jpg" class="photo">
<img src="https://cdn.example.com/pictures/03.jpg" class="photo">
<img src="https://cdn.example.com/pictures/04.jpg" class="photo">
很簡單。但是現在,如果我想將它們全部指向不同的目錄怎么辦?喜歡:/圖片/
到目前為止,我已經嘗試了一些東西,包括這個 jQuery,但到目前為止還沒有成功:
$("img.photo").attr("src").replace("pictures","images");
感覺它應該這樣做,因為它使用該類定位影像 -> 然后是“src”屬性 -> 并告訴它用“影像”替換“圖片”。
但是我對使用 jQuery 非常陌生,所以我很感激一些幫助。
我在這里想念什么?有什么建議嗎?
更新:非常感謝那些提供答案和解釋的人——我非常感謝你幫助初學者!
uj5u.com熱心網友回復:
在您的代碼中,您只需更改回傳的字串,
$("img.photo").attr("src")之后無需對其進行任何操作。這不會更改<img>元素中的屬性。
這應該做的作業:
$("img.photo").each(function(){this.src=this.src.replace("pictures","images")})
在這里,我遍歷所有匹配的元素并將更改后的src字串分配回每個元素的src屬性。
$("img.photo").each(function(){this.src=this.src.replace("pictures","images")});
// list the changed src values in the console:
console.log($("img.photo").map((i,img)=>img.src).get())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://cdn.example.com/pictures/01.jpg" class="photo">
<img src="https://cdn.example.com/pictures/02.jpg" class="photo">
<img src="https://cdn.example.com/pictures/03.jpg" class="photo">
<img src="https://cdn.example.com/pictures/04.jpg" class="photo">
uj5u.com熱心網友回復:
您的代碼片段將不起作用,因為這是獲取src第一個影像的屬性并對其進行更改,但從不將結果設定為元素src上的新結果。<img>
試試這個
$("img.photo").each((index, img) => {
img.src = img.src.replace("pictures","images");
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/426575.html
標籤:javascript html jQuery
