所以我是JQuery和HTML语言的新手,我在控制台中得到了Uncaught ReferenceError: img is not defined
错误。我修复了它,它运行了,但现在它不显示img...有什么建议吗?我的项目应该是一个幻灯片放映,所以当你点击下一步按钮,它会转到下一张图片。我还没有添加所有的照片,因为我想先让它正常工作,但总共会有4张。另外,我使用的是可汗学院的编辑器,所以如果一些变量很奇怪(比如var),这就是为什么。
这是我的主体和脚本代码。谢谢你的帮助!
<body>
<br>
<img>
<button type="button" id="next">Next ➡</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> //access to jQuery library
<script>
var photo=function(nums){
console.log("nums "+nums);//checking to see if the right number was received from the function
if (nums===1){
$("img")//I think the problem is here
.css("src","https://www.kasandbox.org/programming-images/food/mushroom.png")//photo on khan academy
.css("width","400")
.css("alt","Mushrooms");
} else if (nums===2){
$("img")
.css("src","https://www.kasandbox.org/programming-images/food/coffee-beans.png") //photo on khan academy
.css("width","400")
.css("alt","Coffee Beans");
}
$("img").slideDown(1000);
}
$("img").hide();
$("#next").on("click", function() {
var num = 0;
if(num < 4){
num++;
}else{
num = 1;
}
console.log("num "+num);//checking to see if the right number was sent to the function
photo(num);
});
</script>
</body>
发布于 2015-11-18 00:04:26
您需要使用attr()
函数
就像这样
$("img")
.attr("src","https://www.kasandbox.org/programming-images/food/mushroom.png")//photo on khan academy
.attr("width","400")
.attr("alt","Mushrooms");
发布于 2015-11-18 00:06:02
src
和alt
不是CSS属性。它们是HTML属性(或属性)。所以这不会做任何可观察到的事情:
.css("src","https://www.kasandbox.org/programming-images/food/mushroom.png")
但这将会:
.attr("src","https://www.kasandbox.org/programming-images/food/mushroom.png")
发布于 2015-11-18 00:06:38
您正在尝试使用jQuery的css()
函数设置HTML属性,但该函数将不起作用,您需要使用attr()
和width()
$("img")
.attr("src","https://www.kasandbox.org/programming-images/food/mushroom.png")//photo on khan academy
.attr("alt","Mushrooms")
.width("400px");
https://stackoverflow.com/questions/33761458
复制相似问题