jquery - 使用 HTML ID 作为数组

标签 jquery html

<select class="dName" name="dName">
    <option SELECTED value="#" DISABLED>========================</option>
    <option id="0" value="amensah">Abbey-Mensah, Michael</option>
    <option id="1" value="acharya">Acharya, Niraj</option>
    <option id="2" value="achonu">Achonu, Geoffrey C.</option>
    <option id="3" value="agustin">Agustin, Erie</option>
    <option id="4" value="agyemang">Agyemang, Kuragu</option>
</select>

我在 Javascript 中使用 ID:

if (i[iVar] == $(".dName").find('option:selected').attr('id')) {

拉出选择的选项。

现在假设我想删除 dName 选择的选项 #2,而不是将 #3 更改为 #2 作为 ID,将 #4 更改为 #3 作为 ID,我可以使用数组吗?这可能很简单,但有 100 多个选项会非常耗时

是否有办法更改 dName 选择中的 ID,以便无论它用作数组?像这样的东西:

<option id="[]" value="amensah">Abbey-Mensah, Michael</option>

那么如果我删除列表中间的一个选项,它会保持编号结构的顺序吗?

已解决:

if (i[iVar] == $(".dName").find('option:selected').attr('id')) {

已更改为:

if (i[iVar] == "the value of selection option") {

document.getElementById('first').innerHTML = phyList[$(".dName").find('option:selected').attr('id')].firstName;

已更改为:

document.getElementById('first').innerHTML = phyList[$(".dName").find('option:selected').index()-1].firstName; //.index()-1 because the first option is "=" which is not being used

这样我就可以完全摆脱 ID,不用担心删除选项语句。

最佳答案

您根本不需要 ID,无论您在 select 元素中删除什么内容(.remove() ?),都会采用 index所选选项的:

举个例子:

$('select').on('change', function(){
  alert( $(':selected').index() );
});

http://jsbin.com/akefaq/2/edit

关于jquery - 使用 HTML ID 作为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16319671/

相关文章:

javascript - jquery css 显示属性设置为 '' “它是有效用法吗?

javascript - 如何使用 jquery 来防止可编辑的 div 超出我们的限制长度

javascript - 如何在使用find jquery时计算它穿过的元素数量

javascript - 用函数在js中写html

javascript - 将图像纵横比保持在响应大小划分中

javascript - 只需单击一下按钮即可更改网站的一部分

javascript - 忽略 jQuery.when 期间的超时

javascript - 无法使用饼图 Highcharts 显示结果

javascript - 导致内存泄漏的 jQuery 代码

javascript - 循环动画功能