Jquery怎么获取select选中项 自定义属性的值

Jquery怎么获取select选中项 自定义属性的值,第1张

Jquery获取select选中项 自定义属性的值的方法:

示例代码:

1、html代码:

<!DOCTYPE>

<html>

<head>

<meta >

#lili{font-weight:bold;color:red;}

</style>

</head>

<body>

<select id="mysel" title="选择提示">

<option>nba</option>

<option>fifa</option>

</select>

<script>

</script>

</body>

<html>

2、jquery代码获取自定义属性:

使用attr(name)获取title值:

<script>

alert($("#mysel")attr("title"));

</script>

3、显示结果:

1、首先要保证select中每一个option标签都有value属性;

2、jquery的写法

$('#sele')val()//这里假设select的id是sele,这样可以获取当前选中的option的value

3、刚开始没有选择的时候默认的是第一个option的value值;

4、要测试的话可以写一个change事件,也就是每一次选择都会触发

$('#sele')change(function(){

     consolelog($('#sele')val())//每次选择都会输出选择的当前option的value

})

5、如果想在js中刚开始就设置选中某一个,可以

$('#sele')val('值')//在括号中写入你想默认选中的某一个option的value值

纯JS

var e = documentgetElementById("form-field-select-4");

alert(getSelectValues(e));

// Return an array of the selected opion values

// select is an HTML select element

function getSelectValues(select) {

  var result = [];

  var options = select && selectoptions;

  var opt;

  for (var i=0, iLen=optionslength; i<iLen; i++) {

    opt = options[i];

    if (optselected) {

      resultpush(optvalue || opttext);

    }

  }

  return result;

}

JQuery

 var selectedValues = [];    

 $("#form-field-select-4 :selected")each(function(){

     selectedValuespush($(this)val()); 

 });

 alert(selectedValues);

1如果 select 元素下的所有 option 元素均没有指定 selected 属性,会默认选中第一个。

2可以通过 selectselectedIndex 获取到选中的 option 元素的索引。

3可以通过 selectoptions[selectselectedIndex] 获取到选中的 option 元素。

option 元素 <option selected="selected" value="value3">text3</option>,可以通过 optionvalue 获得 option 元素的 value 属性值,即 value3;可以通过 optiontext 获得 option 元素内的文本,即 text3。

4如果 option 元素没有定义 value 属性,则 IE 中 optionvalue 无法获得,但 Safari、Opera、FireFox 依旧可以通过 optionvalue 获得,值同于 optiontext 。

5可以通过 optionattributesvalue && optionattributesvaluespecified 来判断 option 元素是否定义了 value 属性。

6故,获得当前 select 元素值的脚本如下:

var getSelectValue = funtion(select) {

var idx = selectselectedIndex,

option,

value;

if (idx > -1) {

option = selectoptions[idx];

value = optionattributesvalue;

return (value && valuespecified) optionvalue : optiontext);

}

return null;

}

以上就是关于Jquery怎么获取select选中项 自定义属性的值全部的内容,包括:Jquery怎么获取select选中项 自定义属性的值、jquery怎么获取select选中的值,默认选中、JS获取select option获取选中的值多选等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/9311543.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-27
下一篇2023-04-27

发表评论

登录后才能评论

评论列表(0条)

    保存