querySelector()无法修改<input />标记中的值,onblur或onfocus的问题

时间:2018-10-07 19:50:10

标签: javascript html

我一定在搞砸。当我尝试在Javascript中使用querySelector()时,似乎无法修改输入标签的值,onbluronfocus子句,但可以使用JavaScript修改其ID和名称。救命!

我使用以下代码克隆了一大段HTML代码;

const newAdjustment = lastAdjustment.cloneNode(true);

我正在修改的输入标签如下:

<input type="text" class="form-control text-right entered-amount" 
  id="Amount15" name="Amount15" value="$3.00" 
  onfocus="deformatAmount(15)" onblur="recalc(15)">
</input>

使用querySelector()修改输入标签的ID和名称没有问题;

const originalSequenceNumber = 15;
const newSequenceNumber = originalSequenceNumber + 1;
const originalAIdName = 'Amount' + originalSequenceNumber;
const newAIdName = 'Amount' + newSequenceNumber;
newAdjustment.querySelector("#" + originalAIdName).id = newAIdName;
newAdjustment.querySelector("#" + newAIdName).name = newAIdName;

这给我留下了以下内容;

<input type="text" class="form-control text-right entered-amount" 
  id="Amount16" name="Amount16" value="$3.00" 
  onfocus="deformatAmount(15)" onblur="recalc(15)">
</input>

然后我尝试使用以下内容修改值onbluronfocus

const newAOnfocus = 'deformatAmount(' + newSequenceNumber + ')';
const newAOnblur = 'recalc(' + newSequenceNumber + ')';
newAdjustment.querySelector("#" + originalAIdName).value = "$0.00 ";
newAdjustment.querySelector("#" + newAIdName).onfocus = newAOnfocus;
newAdjustment.querySelector("#" + newAIdName).onblur = newAOnblur;

什么也没发生。 newAOnFocusnewOnBlur和输入元素如下;

newAOnfocus       =  deformatAmount(16)
newAOnblur        =  recalc(16)
newAdjustment     =  <input type="text" class="form-control text-right entered-amount" id="Amount16" name="Amount16" value="$3.00" onfocus="deformatAmount(15)" onblur="recalc(15)">

将子项附加到文档并使用document.querySelector()后,我可以修改值,但不能修改onbluronfocus子句。我究竟做错了什么? querySelector()中缺少什么条款?顺便说一句,newAdjustment中有三个输入和三个按钮标签,而六个都存在相同的问题。

关于.value的更正 .value已正确更新。该页面在.value中反映了正确的值,但是当我对console.log()进行newAdjustment时,它显示了克隆(.cloneNode())的原始值。我想知道其余的我是否也有同样的问题,这意味着我实际上根本没有问题。还有更多的测试。

1 个答案:

答案 0 :(得分:2)

您可以在输入中使用setAttribute

所以

newAdjustment.querySelector("#" + originalAIdName).value = "$0.00 ";
newAdjustment.querySelector("#" + newAIdName).onfocus = newAOnfocus;
newAdjustment.querySelector("#" + newAIdName).onblur = newAOnblur;

成为

newAdjustment.querySelector("#" + originalAIdName).setAttribute("value", "$0.00 ");
newAdjustment.querySelector("#" + newAIdName).setAttribute("onfocus", newAOnfocus);
newAdjustment.querySelector("#" + newAIdName).setAtribute("onblur", newAOnblur);