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

时间:2015-10-28 11:01:42

标签: javascript jquery javascript-events scope

我想基于全局状态变量更改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的值是什么,但我不知道如何解决它。

1 个答案:

答案 0 :(得分:1)

使用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);
    }
});
相关问题