gpt4 book ai didi

javascript - 有没有办法将 for 循环的索引传递给按钮对象(jQueryUI-dialog)中的单击函数?

转载 作者:行者123 更新时间:2023-12-01 04:34:58 25 4
gpt4 key购买 nike

在我的 map 应用程序中,我尝试实现一个 jQueryUI 对话框,其中包含动态数量的按钮,具体取决于搜索表单产生的点击次数。这些按钮调用 showResults() 方法,该方法导航到与单击的命中相对应的标记。

问题是,无论您单击哪个按钮,它总是会导航到命中数组的最下面。我知道这是由于点击事件造成的,因此当它被触发时,变量 hit 将始终包含最后一个条目 hit[hit.length-1]

我现在唯一的解决方法是为每个可能的点击量定义单独的函数,我在 div.dialog-object 中“定期”定义按钮,而不是在 for 循环中,但这会导致很多冗余代码。

这是我的代码:

function multiplehits(message, names, sites) {

var buttons = [];

for (var i=0; i < hits.length; i++){
var hit = hits[i];
var button = {
text: names[i]+", "+sites[i],
click: function () {
div.remove();
showResults(hit); /*always navigates to the last entry of the hits array*/
$(this).dialog("close");
}
}
buttons.push(button);
}
var div = $('<div>');
div.html(message);
div.dialog({
close: function( event, ui ) {
hits = [];
},
closeText: 'close',
autoOpen: true,
modal: true,
draggable: false,
resizable: false,
title: OpenLayers.i18n('Title'),
buttons: buttons
});
}

是否有某种技巧将正确的索引传递给点击函数?由于我为此使用 jQuery 按钮,因此我认为我必须坚持对象结构 button = {text,click:function(){})

最佳答案

最快的方法:

替换:

var hit = hits[i];

与:

let hit = hits[i];
<小时/>

正确的方法:

了解 JavaScript 闭包、IIFE、.bind 方法以及 ES6 的新功能。

这个其他question是一个很好的起点。

<小时/>

代码片段

var hits = [1,2,3];
var names = ['a','b','c'];

var buttons = [];

function showResults(hit){
console.log(hit);
}

for (var i=0; i < hits.length; i++){
let hit = hits[i];
var button = {
text: names[i],
click: function () {
div.remove();
showResults(hit); /*always navigates to the last entry of the hits array*/
}
}
buttons.push(button);
}
var div = $('<div>');
div.html("message");
div.dialog({
close: function( event, ui ) {
hits = [];
},
closeText: 'close',
autoOpen: true,
modal: true,
draggable: false,
resizable: false,
title: 'Title',
buttons: buttons
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>

关于javascript - 有没有办法将 for 循环的索引传递给按钮对象(jQueryUI-dialog)中的单击函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59217162/

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