在选择选项标记中使用javascript访问具有多个值的值 [英] Access values in select option tag with more than one value using javascript

查看:81
本文介绍了在选择选项标记中使用javascript访问具有多个值的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 < script type =text / javascript> 
函数showDiv(divID,val){
var text = val.value;
alert(text);
}
< / script>

鼠标:< select onChange =showDiv('#mouse',this);>
< option value =>选择鼠标类型< / option>
< option value ={'text':'Normal','id':'normalMouse'}>普通< / option>
< option value ={'text':'Gaming','id':'gamingMouse'}>游戏< / option>
< / select>

输出结果为:


{'text':'Normal','id':'normalMouse'}

但输出应该是只有'正常'。这意味着我想单独访问这些值。如何做到这一点?

根据 w3c org选项 doc的值只能有字符串值,所以需要将其转换为对象。






工作小提琴

Javascript代码

  function showDiv(divID,val){
var value = eval('('+ val.value +')');
alert('Text:''+ value ['text'] +'Id:'+ value ['id'] +'''');
}






正如@Johan所说的使用 eval()不是一种安全的方法。因此,对于安全性更为关注的情况 使用JSON.parse的工作小提琴


$ b

HTML

 < option value ='{text:Normal,id:normalMouse} >正常< /选项> 
< option value ='{text:Gaming,id:gamingMouse}'> Gaming< / option>

Javascript

  function showDiv(divID,val){
var value = JSON.parse(val.value);
alert('Text:''+ value ['text'] +'Id:'+ value ['id'] +'''');
}






希望它有助于.. !!


Here is my code.

<script type="text/javascript">
    function showDiv(divID,val) {
        var text= val.value;
        alert(text);
    }
</script>

Mouse:<select onChange="showDiv('#mouse',this);">
    <option value="">Select Mouse Type</option>
    <option value="{'text':'Normal','id':'normalMouse'}">Normal</option>
    <option value="{'text':'Gaming','id':'gamingMouse'}">Gaming</option>
</select>

The output is:

{'text':'Normal','id':'normalMouse'}

But The output should be 'normal' only. That means I want to access to those values separately.How to do that?

解决方案

As per w3c org option doc's value can have only string value so it is necessary to convert it into object..


Working fiddle
Javascript code

function showDiv(divID, val) {
    var value = eval('(' + val.value + ')');
    alert('Text: "' + value['text'] + '" Id: "' + value['id'] + '"');
}  


As @Johan say's using eval() is not a safe method.. So for the scenarios where safety is even concerned Working Fiddle using JSON.parse

HTML

<option value='{"text":"Normal","id":"normalMouse"}'>Normal</option>
<option value='{"text":"Gaming","id":"gamingMouse"}'>Gaming</option>  

Javascript

function showDiv(divID, val) {
    var value = JSON.parse(val.value);
    alert('Text: "' + value['text'] + '" Id: "' + value['id'] + '"');
}


Hope it helps..!!

这篇关于在选择选项标记中使用javascript访问具有多个值的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆