有没有办法让它工作?
我读过“let 只能在它声明的范围内可用,就像在 for 循环中一样,另一方面,“var”可以在循环外访问,例如”
HTML:
let create = document.getElementById("create");
let add = document.getElementById("add");
let cart = document.getElementById("cart");
create.onclick = function(){
var foo = "foo";
console.log(foo);
}
add.onclick = function(){
cart.innerHTML += foo;
}
<!DOCTYPE html>
<html>
<body>
<button id="create">create</button>
<button id="add">Add to cart</button>
<h2 id="cart">Cart: </h2>
</body>
<script type="text/javascript" src="test.js"></script>
</html>
您可以通过传递变量来附加点击事件处理函数add
内部的show
点击事件:
let show = document.getElementById("show");
let add = document.getElementById("add");
let cart = document.getElementById("cart");
show.onclick = function(){
var foo = "foo";
console.log(foo);
add.addEventListener('click', function() { addToCart(foo); });
}
function addToCart(f){
cart.innerHTML += f;
}
<button id="show">Show</button>
<button id="add">Add to cart</button>
<h2 id="cart">Cart: </h2>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句