2013-01-15 16 views
0

我见到目前为止以下二维数组值:JavaScript的获得根据所选的下拉文本字符串

<!DOCTYPE HTML> 
<html> 
    <head> 
    <meta http-equiv="content-type" content="text/html" /> 
    <script src="http://code.jquery.com/jquery-latest.js"></script> 
    <title> 
     Select Value From Array 
    </title> 
    </head> 
    <body> 

    <script type="text/javascript"> 
     var KeysArray = { 
      "Lake":"imageabc.jpg", 
      "House":"imagedef.jpg", 
      "PC":"imageghi.jpg", 
      "Sky":"imagejkl.jpg" 
     } 
     $(function(){ 
      $('.product').change(function() { 
       var xkey = $.trim($(".product option:selected").text()); 
       // alert(xkey); 
      }); 
     }); 
    </script> 

    <div> 

     <select class="product" title=""> 
     <option value=""> 
      -- Select -- 
     </option> 
     <option value="123"> 
      Lake 
     </option> 
     <option value="456"> 
      House 
     </option> 
     <option value="789"> 
      PC 
     </option> 
     <option value="101"> 
      Sky 
     </option> 
     </select> 

    </div> 

    </body> 
</html> 

一旦我们选择从下拉的值,我需要比较它与选项的文本值现有的通讯对象数组值。

因此,如果用户选择“House”,我应该检查是否存在具有该名称的键,如果是,我需要获取它的数组值。因此在“House”例子中它应该返回“imagedef.jpg”。

任何人都可以请帮忙吗?谢谢!

回答

1

我设法让他为你工作的this的jsfiddle。

你需要做的是让在KeysArray对象在此线路上正确的密钥:

var xkey = KeysArray[ $.trim($(".product option:selected").text()) ]; 

或者,也可以在2个步骤做是为了提高可读性。

var xkey = $.trim($(".product option:selected").text()); 
xkey = KeysArray[xkey]; 

这可能是值得检查,看看如果键在继续之前确实存在。我会建议在获得xkey后进行检查。

if (typeof xkey !== 'string') { xkey = 'Not found'; } 
0

尝试以此为平变化回调函数体

var xkey = $.trim($(".product option:selected").text()); 
alert(KeysArray[xkey] || 'Not found'); 

我希望这有助于。

1
$('.product').change(function() { 
    var xkey = $.trim($(".product option:selected").text()); 
    alert(KeysArray[xkey]); 
}); 
相关问题