gpt4 book ai didi

javascript - 在 Jquery 事件处理程序中无法访问在文档内部声明的变量就绪

转载 作者:行者123 更新时间:2023-11-30 11:46:40 25 4
gpt4 key购买 nike

var ay = 0;
$(document).ready(function() {
var ax = 0;
$(document).on("click", "a[href$=#icom_add_to_cart]", function(event) {
event.preventDefault();
console.log(ax); // not accessible
console.log(ay); // accessible
}

请帮助我理解为什么在 onclick 事件处理程序中无法访问 ax 而可以访问 ay。我有一个变量,我必须在 document.ready 中的多个 onclick 处理程序中访问它。声明此变量的最佳做法应该是怎样的。 Chrome console source

prods is available but catIds is not at the location of debug

如您在调试位置所见,“prods”可用,但“catIds”未定义。

最佳答案

除了不使用 }) 关闭你的脚本外, 它工作正常,虽然我不理解你的 anchor ,所以我在代码段中更改了它们。

片段

var az = 3
$(document).ready(function() {
var ax = 2;
var ay = 1;
$(document).on("click", "a[href^=#add]", function(event) {
event.preventDefault();
console.log(ax);
console.log(ay);
console.log(az);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href='#add1'>+1</a>
</li>
<li><a href='#add2'>+2</a>
</li>
<li><a href='#add3'>+3</a>
</li>
<li><a href='#add4'>+4</a>
</li>
<li><a href='#add5'>+5</a>
</li>
</ul>

关于javascript - 在 Jquery 事件处理程序中无法访问在文档内部声明的变量就绪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40762623/

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