开发者

JavaScript event object is not being populated in event handler function

I have the following code:

Html:

<tr>
    <td 开发者_运维百科onclick="ThingClicked()">click me</td>
</tr>

JS:

function ThingClicked(event) {
    var row = event.currentTarget.parent("tr");
    callAnotherDOMManipulatingFunction(row);
}

For some reason, event.currentTarget is undefined. I tried 'this' but that was undefined aswell. What's going on? How do I get the row that this td is contained in?


Well, since you included a jQuery tag (and included a link to jQuery docs), I'll show you how that way.

EDIT:

jQuery live() docs

jQuery clone() docs

EDIT: Added jQuery's ready() function. You will always place your code inside as shown.

$('document').ready(function() {
    $('td').click(function() {
        var row = $(this).closest('tr');
        callAnotherDOMManipulatingFunction(row);
    });
});

Of course, this will attach a click event to every td tag, but you get the idea.

EDIT:

Further explanation. When using jQuery, you typically will assign events in your javascript, not in HTML. Assigning to 'td' will give the click event to every 'td' tag on the page, so it may be that you will instead give the 'td' a class and use that to attach the event, like:

$('.myFreakingAwesomeClass').click(function() {
    ...
});

You won't often need to reference 'event', but it does come in handy at times.


Try this:

<tr>
  <td onclick="javascript:ThingClicked(this);">click me</td>
</tr>

function ThingClicked(td) {
    callAnotherDOMManipulatingFunction(td.parentNode);
}


Change your code like this:

Html:

<tr>
    <td onclick="ThingClicked(this)">click me</td>
</tr>

JS:

function ThingClicked(element) {
    callAnotherDOMManipulatingFunction(element);
}


Try this:

<tr>
    <td onclick="ThingClicked(event)">click me</td>
</tr>

with the input parameter of your handler function specially called event and nothing else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜