我试图在Javascript中创建具有唯一Id的新节点。为此,我创建了一个按钮
<input type="button" value="Add Field" onclick="AddField(this.parentElement);" />和Javascript函数
AddField = function (ParentDom){
var uniqueValue = ParentDom.children.length;
var newNode = "<input id='InputName"+uniqueName+"' type='text' dir='ltr' autocomplete='on' class='form-field marge-top-20' placeholder='Name Eng' value='' oninput='SafeCopy(this, document.getElementById('inputName"+uniqueName+"')); return false;'>";
//here will be a code to add `newNode` as last child to `ParentDom`
}但是,当我调试代码时,我得到了
newNode = <input id="InputName7" type="text" dir="ltr" autocomplete="on" class="form-field marge-top-20" placeholder="Name Eng" value="" oninput="SafeCopy(this, document.getElementById(" inputname7'));="" return="" false;'="">我不明白为什么
id="InputName7"
很管用,但是
document.getElementById(" inputname7'));="" return="" false;'=""
搞砸了。
在许多建议在单引号中添加反斜杠的答案之后,我仍然会得到混乱的结果:
代码:
<input id=\'InputName" + uniqueName + "\' type='text' dir='ltr' autocomplete='on' class='form-field marge-top-20' placeholder='Name Eng' value='' oninput='SafeCopy(this, document.getElementById(\'inputName" + uniqueName + "\')); return false;'>结果:
"<input id="InputName7" type="text" dir="ltr" autocomplete="on" class="form-field marge-top-20" placeholder="Name Eng" value="" oninput="SafeCopy(this, document.getElementById(" inputname7'));="" return="" false;'="">"请帮帮我!
发布于 2017-08-22 12:07:17
终于成功了!在最后,没有必要添加反斜杠!需要做的是删除单引号中的所有单引号,代码可以工作:
var newNode = "<input id='InputName"+uniqueName+"' type='text' dir='ltr' autocomplete='on' class='form-field marge-top-20' placeholder='Name Eng' value='' oninput=SafeCopy(this, document.getElementById('inputName"+uniqueName+"'))>";而且起作用了!
问题是这样的代码:
'SafeCopy(this, document.getElementById('inputName"+uniqueName+"')); return false;'如您所见,我在单引号中有一个单引号。在我把它改成:
SafeCopy(this, document.getElementById('inputName"+uniqueName+"'))它的工作原理是应该的!
发布于 2017-07-30 17:45:59
您需要将反斜杠放在单引号之前,否则代码将在oninput中混乱。
oninput='SafeCopy(this, document.getElementById(\'inputName"+uniqueName+"\')); return false;'发布于 2017-07-30 17:45:24
你的内心格言是无法逃脱的。您应该在此部分中的单引号之前添加反斜杠:
document.getElementById('inputName"+uniqueName+"')因为它们发生在一个已经被单引号引用的部分。所以:
document.getElementById(\'inputName"+uniqueName+"\')(在更正您的问题之前,您使用了<div class='block'>,它被忽略了,因为您没有关闭标记。)
同时检查inputName的资本化程度。可能应该是InputName。但你还是觉得很奇怪,你想打电话给:
SafeCopy(this, document.getElementById(\'InputName"+uniqueName+"\')..。因为这两个参数都将引用相同的元素,即触发事件的input。
https://stackoverflow.com/questions/45402747
复制相似问题