gpt4 book ai didi

JavaScript onClick 参数表示变量未定义

转载 作者:行者123 更新时间:2023-11-28 18:42:12 25 4
gpt4 key购买 nike

Uncaught ReferenceError: PAGEHTML is not defined

我的对象是在我的 JS 中定义的,为什么会返回错误?我已经通过其他 onclicks 传递了对象名称。

HTML

<button id="addLocation" onclick="insertBefore(PAGEHTML.uarAddLocation, addLocation)">+ Add Location</button>

JS 对象

var PAGEHTML = {
uarAddLocation: `<label for="amountUnusual">Amount of Unusual Activity</label>
<input id="amountUnusual" class="number" />
<div class="fourtyFiveWidth inlineBlock">
<label for="fromDate">Unusual Activity Start Date</label>
<input id="fromDate" class="datepicker number" />
</div>
<div style="margin-left: calc(10% - 4px)" class="fourtyFiveWidth inlineBlock">
<label for="toDate">Unusual Activity End Date</label>
<input id="toDate" class="datepicker number" />
</div>
<label for="AULocation">Unusual Activity Location</label>
<input id="AULocation" />`;
};

JS 函数

function insertBefore(selector, html){
console.log("selector: "+selector);
$(html).insertBefore("#"+selector);
};

最佳答案

在你的 onclick 中:

onclick="insertBefore(PAGEHTML.uarLocation, addLocation)"
  • 您将 HTML (PAGEHTML.uarAddLocation) 作为选择器传递
  • addLocation 必须用引号引起来
  • PAGEHTML.uarLocation 不存在,但 PAGEHTML.uarAddLocation 存在
  • 您的函数必须有不同的名称,这会导致 native insertBefore 出现问题

所以应该是这样的:

onclick="insertBefor('addLocation', PAGEHTML.uarAddLocation)"

这是一个工作片段:

var PAGEHTML = {
uarAddLocation: `<label for="amountUnusual">Amount of Unusual Activity</label>
<input id="amountUnusual" class="number" />
<div class="fourtyFiveWidth inlineBlock">
<label for="fromDate">Unusual Activity Start Date</label>
<input id="fromDate" class="datepicker number" />
</div>
<div style="margin-left: calc(10% - 4px)" class="fourtyFiveWidth inlineBlock">
<label for="toDate">Unusual Activity End Date</label>
<input id="toDate" class="datepicker number" />
</div>
<label for="AULocation">Unusual Activity Location</label>
<input id="AULocation" />`
};

function insertBefor(selector, html){
console.log("selector: " + selector);
$(html).insertBefore("#"+selector);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addLocation" onclick="insertBefor('addLocation', PAGEHTML.uarAddLocation)">+ Add Location</button>

关于JavaScript onClick 参数表示变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35953043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com