我有一个带有 JavaScript 的小型基本 html 代码。我想要的只是当我输入 3 时,它应该显示指定的图像以及相应的 9 图像。这是演示。访问http://jsbin.com/UVOFeGIG/1/edit
它在那里工作。我不知道为什么 JavaScript 不能这样工作。有人能解决这个问题吗?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
var num2img = {
"3":"visa",
"9":"mastercard"
};
$('#num').on('input', function(){
var val = this.value;
if(val.length<=1){
var n = this.value.charAt(0);
if(val && num2img[n]!==undefined){
$('#cardImage')[0].src = 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.png';
}else{
$('#cardImage')[0].src = 'http://placehold.it/100x100/cf5';
}
}
});
</script>
<meta charset=utf-8 />
<title>Demo by Roko C.B.</title>
</head>
<body>
<input id="num"><br>
<img id="cardImage" src="http://placehold.it/100x100/cf5">
</body>
</html>
最佳答案
试试这个
$(document).ready(function(){
var num2img = {
"3":"visa",
"9":"mastercard"
};
$('#num').keyup(function(){
var val = this.value;
if(val.length<=1){
var n = this.value.charAt(0);
if(val && num2img[n]!==undefined){
$('#cardImage')[0].src = 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.png';
}else{
$('#cardImage')[0].src = 'http://placehold.it/100x100/cf5';
}
}
});
});
关于javascript - 给出输入后更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20045861/