سؤال

I cannot seem to get event.target to work for an element that is nested in any sort of tag in a body element. I'm capturing Javascript keystrokes and updating them into an array, like so:

$(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;
        }
    }
}

Then after a button is clicked that signals the playback to begin, I update the text field to simulate live typing:

    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();
        }
    }
}

In the action() function, the targetValue is the actual value of the text field, and the targetElement is the actual text field element. This code works beautifully when the text field is just in the body tag, but nesting it within any sort of tag such as div, it doesn't work at all.

هل كانت مفيدة؟

المحلول

I fixed it. As it turns out there was a call where I was changing the HTML of the page, which messed up my element ID's.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top