gpt4 book ai didi

javascript - 具有动态创建元素的事件处理程序的全局变量范围

转载 作者:行者123 更新时间:2023-11-27 23:44:14 26 4
gpt4 key购买 nike

我想根据全局状态变量更改 Bootstrap 下拉列表的行为。如果单击时 uiState 变量为 'normal',则应显示下拉列表,但如果处于其他状态,则应执行其他操作。我有以下代码:

$(document).ready(function () {
var uiState = 'normal';

// Load HTML for word control from server
var wordUiElement;
$.get('/static/word_ui_element.html', function (data) {
wordUiElement = data;
});
var nwords = 0;
var testClickCounter = 0;

// Make it so dropdowns are exclusively controlled via JavaScript
$(document).off('.dropdown.data-api')

$('#ui-add-word').click(function (event) {
var control = wordUiElement.replace(/wx/g, 'w' + nwords.toString());
$('#ui-spec').append(control);
nwords++;
});

$('#ui-change-state').click(function (event) {
if (uiState === 'word_select') {
uiState = 'normal';
} else {
uiState = 'word_select';
}
console.log(uiState);
});

$('#ui-spec').on('click', '.dropdown .dropdown-toggle', function (event) {
if (uiState === 'normal') {
$(this).dropdown('toggle');
}
else {
testClickCounter ++;
console.log(testClickCounter);
}
});

});

但是,当动态创建下拉菜单时,它们的行为似乎是根据创建下拉菜单时的 uiState 变量来固定的。

这意味着,如果在 uiState 变量设置为 'normal' 时创建下拉菜单,则无论 uiState 是什么时候单击后,它将始终显示或隐藏下拉列表。另一方面,如果在 uiState'word_select' 时创建下拉列表,它将始终递增并记录 testClickCounter。就好像处理程序中的 if 语句在创建下拉列表时计算一次,并保留创建时的 uiState 值。

我认为这是一个范围问题,并且事件处理程序在创建时执行。我希望它在点击时检查 uiState 的值是什么,但我不知道如何修复它。

最佳答案

使用data-toggle="dropdown"实例化元素,并在状态更改时删除此属性,例如:

$('#wx').attr('data-toggle',''); // Dropdown no longer shows

$('#wx').attr('data-toggle','dropdown'); // Dropdown shows again

触发器的其余部分照常继续:

$('#wx').on('click', '.dropdown .dropdown-toggle', function (event) {
if (uiState !== 'normal') {
testClickCounter ++;
console.log(testClickCounter);
}
});

关于javascript - 具有动态创建元素的事件处理程序的全局变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33389296/

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