在给出输入时更改图像

Change an image when input is given

本文关键字:图像 输入      更新时间:2023-09-26

我有一个带有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';
         }
      }
    });
});

演示

尝试这样的事情

$(function(){
    // you have not given any event
    $('#num').on('keyup', function(){
      var val = this.value;
      if(val.length){//your length checking logically wrong
         var n = this.value.charAt(0);
         if(val && num2img[n]!==undefined){
           $('#cardImage')[0].src = 'data/1357696142_mastercard1'+ num2img[n] +'.gif';
         }else{
           $('#cardImage')[0].src = 'http://placehold.it/100x100/cf5';
         }
      }
    });
})

您需要将 $('#cardImage')[0] 更改为 $('#cardImage').attr('src' , 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.png'); 因为 # 将返回一个元素替换 请参阅jsfiddle http://jsfiddle.net/mailtoshebin/dMWmw/

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').attr('src' , 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.png');
     }else{
       $('#cardImage')[0].src = 'http://placehold.it/100x100/cf5';
     }
  }
});

尝试在输入框上捕获"按键"事件,http://api.jquery.com/keypress/或尝试在输入框中捕获"更改"事件,http://api.jquery.com/change/

将脚本代码放在里面

$(document).ready(function(){
    //your code goes here
});

并替换

$('#cardImage')[0].src = 'data/1357696142_mastercard1'+ num2img[n] +'.gif';

$('#cardImage')[0].src = 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.gif';