jQuery在分配“选定”属性时行为不一致

jQuery behaving inconsistently when assigning "selected" attributes

本文关键字:不一致 属性 分配 选定 jQuery      更新时间:2023-09-26

我有一个表单来编辑表中的记录。我将表的所有记录的字段值存储在 javascript 数组中,每个字段一个数组。当用户选择要编辑的记录时,我会从数组中填充表单字段。

表的三个字段是外键,对于这些字段,我使用 SELECTS 包含父表中所有可用记录。 其中两个 FK 引用同一表。

<select name="parentselector" id="parentselector"  class="cp-form-select" size="1" autofocus required>
    <option id="parentselector-3" value="3">LOCAL SHIRE</option>
    <option id="parentselector-6" value="6">ACCOUNTS</option>
    <option id="parentselector-7" value="7">PARKS AND GARDENS</option>
    <option id="parentselector-8" value="8">ROADS</option>
    <option id="parentselector-9" value="9">MINOR ROADS</option>
</select>
<select name="creditselector" id="creditselector"  class="cp-form-select" size="1" autofocus required>
    <option id="creditselector-76" value="76">FIRST ACCOUNT</option>
    <option id="creditselector-78" value="78">SECOND ACCOUNT</option>
    <option id="creditselector-79" value="79">THIRD ACCOUNT</option>
</select>
<select name="debitselector" id="debitselector"  class="cp-form-select" size="1" autofocus required>
    <option id="debitselector-76" value="76">FIRST ACCOUNT</option>
    <option id="debitselector-78" value="78">SECOND ACCOUNT</option>
    <option id="debitselector-79" value="79">THIRD ACCOUNT</option>
</select>

如果我使用 javescript 来设置所选选项,它可以正常工作:

document.getElementById("debitselector-" + dr).selected = "true";
document.getElementById("creditselector-" + cr).selected = "true";
document.getElementById("parentselector-" + pr).selected = "true";

DR、CR 和 PR 是我的数组中的外键值。

当我使用jQuery时,它非常不可靠。我尝试了以下两种方法 - 没有区别:

$("#debitselector  option[value=" + dr + "]").attr("selected","selected");
$("#creditselector option[value=" + cr + "]").attr("selected","selected");
$("#parentselector option[value=" + pr + "]").attr("selected","selected");
$("#debitselector-" + dr).attr("selected","selected");
$("#creditselector-" + cr).attr("selected","selected");
$("#parentselector-" + pr).attr("selected","selected");

当我第一次加载页面时,默认情况下会加载表中的第一条记录,并且 SELECT all 会正确填充。如果我选择另一条记录进行编辑,则所有三个 SELECT 将再次按预期显示其新值。如果我单步执行代码,我会看到三行代码中的每一行都执行。但是,在那之后,如果我选择第二条记录进行编辑(以及此后),则 SELECTS 不会更改。当我跳过上面的第一行代码时,它似乎崩溃了 - 焦点返回到表单,SELECTS 没有改变。显然,执行已遇到异常并退出。有时,下次我单击表单的任何地方时,代码会在填充物深处的一行中断.js这似乎是 chrome 扩展名 - 我从未接触过这个文件。

我有我的解决方法 - 只是使用 Javascript - 但我很好奇是否有人可以揭示明显"片状"的 jQuery 行为。

您是否尝试过以下方法?只需设置选择值:

  $("#debitselector").val(dr);  
  $("#creditselector").val(cr);  
  $("#parentselector").val(pr);

应该这么简单。请记住,变量 (dr,cr,pr) 必须设置为现有选项值。

不要忘记链接 change() 方法,如果你仍然想在这些方法上触发 onchange 事件。例:

  $("#debitselector").val(dr).change();  

设置 selectedchecked 属性的正确 jQuery 方法是使用 .prop() 方法,如下所示:

$("#your-radio-element").prop("selected", true);
$("#your-checkbox-element").prop("checked", true);

有关更多详细信息,请阅读 jquery .prop() 文档