[英]JavaScript Get two dimensional array value based on selected drop down text string
到目前為止,我有以下內容:
<!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”,則應檢查是否存在具有該名稱的鍵,如果是,則需要獲取它的數組值。 因此,在“房屋”示例中,它應返回“ imagedef.jpg”。
有人可以幫忙嗎? 謝謝!
$('.product').change( function() {
var xkey = $.trim( $(".product option:selected").text() );
alert(KeysArray[xkey]);
});
我設法使其在此 jsfiddle上為您工作。
您需要做的是在此行的KeysArray對象中獲取正確的密鑰:
var xkey = KeysArray[ $.trim( $(".product option:selected").text() ) ];
或者,您可以分兩步執行此操作以提高可讀性。
var xkey = $.trim( $(".product option:selected").text() );
xkey = KeysArray[xkey];
在繼續操作之前,可能值得檢查一下該密鑰是否確實存在。 我建議在得到xkey之后再檢查一下。
if (typeof xkey !== 'string') { xkey = 'Not found'; }
嘗試將此作為onchange回調函數主體
var xkey = $.trim( $(".product option:selected").text() );
alert(KeysArray[xkey] || 'Not found');
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.