[英]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.