给出输入时更改图像

时间:2013-11-18 10:47:32

标签: javascript jquery html

我有一个带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>

5 个答案:

答案 0 :(得分:1)

试试这个

$(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';
         }
      }
    });
});

DEMO

答案 1 :(得分:1)

尝试这样的事情

$(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';
         }
      }
    });
})

答案 2 :(得分:1)

您需要将$('#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';
     }
  }
});

答案 3 :(得分:0)

将脚本代码放在

$(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';

答案 4 :(得分:0)

尝试在输入框http://api.jquery.com/keypress/ OR上捕获“keypress”事件 尝试在输入框http://api.jquery.com/change/

上捕获“更改”事件