event.target不适用于嵌套元素?

时间:2014-01-01 03:33:04

标签: javascript jquery javascript-events

我似乎无法使event.target适用于嵌套在body元素中任何类型标记中的元素。我正在捕获Javascript键击并将它们更新为数组,如下所示:

$(document).keyup(function(event) {

    // Check for human
    if (event.originalEvent !== undefined)
       updateEvents("keyup", event.target, $(event.target).val());

});

function updateEvents(targetEvent, targetElement, targetValue)
{
    if (canUpdate)
    {
        var index = events.length - 1;

        if (events[index].targetEvent !== undefined)
        {
            events[index].targetEvent = targetEvent;
            events[index].targetElement = targetElement;
            events[index].targetValue = targetValue;
        }
    }
}

然后在点击一个按钮以指示播放开始后,我更新文本字段以模拟实时输入:

    var count = 0;

    $.each(events, function() {

        window.setTimeout(action, 100 * count, count);

        count++;

    });

function action(index)
{
    var targetEvent = events[index].targetEvent;
    var targetElement = events[index].targetElement;
    var targetValue = events[index].targetValue;

    if (typeof targetEvent != "undefined")
    {
        if (targetEvent == "keyup")
        {
            // Simulate live typing.
            $(targetElement).val(targetValue);
            // Retain cursor position and user viewpoint in text fields and textareas.
            var length = $(targetElement).val().length;
            targetElement.setSelectionRange(length, length);
            targetElement.scrollLeft = targetElement.scrollWidth;
            targetElement.scrollTop = targetElement.scrollHeight;
            $(targetElement).keyup();
        }
    }
}

action()函数中,targetValue是文本字段的实际值,targetElement是实际的文本字段元素。当文本字段位于body标记中时,此代码可以很好地工作,但是将其嵌套在任何类型的标记(如div)中,它根本不起作用。

1 个答案:

答案 0 :(得分:2)

我修好了。事实证明有一个调用,我正在改变页面的HTML,这搞砸了我的元素ID。