![](/img/trans.png)
[英]How to change image source based on its class in jQuery, after the page has loaded
[英]JQuery: Change image on page based on class in body
我有一個wordpress頁面,我想在首頁的標題上顯示特色圖片,但沒有其他頁面。 我設置了一個腳本,以讀取body標簽是否包含“ home”類,並基於該類顯示圖像。 代碼如下:
<script>
if($('body').hasClass("home")) {
$('#headshot').html('<img src="http://www.kieferslaton.com/wp-content/uploads/2015/04/Headshot1.png" alt="headshot">');
}
</script>
這個腳本怎么了?
嘗試將您的代碼包裝到在DOM就緒時觸發的函數中:
<script>
$(function() {
if($('body').hasClass("home")) {
$('#headshot').html('<img src="http://www.kieferslaton.com/wp-content/uploads/2015/04/Headshot1.png" alt="headshot">');
}
});
</script>
jQuery需要知道何時啟動該函數。 准備好文檔后再啟動它。
$(document).ready(function(){
if($('body').hasClass("home")) {
$('#headshot').html('<img src="http://www.kieferslaton.com/wp-content/uploads/2015/04/Headshot1.png" alt="headshot">');
}
});
您是否在標題部分包含了jQuery庫? 另外有時候$符號可能在wordpress中發生沖突,以這種方式在初始化jQuery時寫完整的jQuery術語:
jQuery(document).ready(function(){
if($('body').hasClass("home")) {
$('#headshot').html('<img src="http://www.kieferslaton.com/wp-content/uploads/2015/04/Headshot1.png" alt="headshot">');
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.