gpt4 book ai didi

javascript - JQuery 在 2 个函数中将参数作为变量传递返回未定义

转载 作者:行者123 更新时间:2023-11-28 17:37:22 25 4
gpt4 key购买 nike

我有以下代码,但我不知道为什么它在“查看和单击”函数中返回“trackingIds[i]”为未定义...我想填充一个数组,代码应该遍历每个数组索引并检查是否有元素悬停或单击。第一个函数中的 el_id 和trackingIds[i] 返回正确的值。我将不胜感激任何帮助,因为我似乎无法弄清楚这一点。

jQuery(document).ready(function(){
var trackingIds = ["elementid"];

for(i=0; i<trackingIds.length; i++){
var el_id = jQuery('#'+trackingIds[i]);
console.log(el_id);
console.log(trackingIds[i]);
el_id.click(function() { Click(trackingIds[i]);});
el_id.mouseover(function() { View(trackingIds[i]);});
}
});

function Click(a) {
//do stuff...
console.log("Click was called from:"+a);
}

function View(b){
// do stuff..
console.log("View was called from:"+b)
}

最佳答案

您需要在 for 循环 中使用 let

jQuery(document).ready(function() {
var trackingIds = ["elementid"];

for (let i = 0; i < trackingIds.length; i++) {
var el_id = jQuery('#' + trackingIds[i]);
//console.log(el_id);
//console.log(trackingIds[i]);
el_id.click(function() {
Click(trackingIds[i]);
});

el_id.mouseover(function() {
View(trackingIds[i]);
});
}
});

function Click(a) {
//do stuff...
console.log("Click was called from: " + a);
}

function View(b) {
// do stuff..
console.log("View was called from: " + b)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id='elementid'>Click me!</h1>

资源

  • let

    The let statement declares a block scope local variable, optionally initializing it to a value.

关于javascript - JQuery 在 2 个函数中将参数作为变量传递返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48794857/

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