开发者

How do I pass in event in javascript?

The javascript code is like below.

var ADDRESS = {
    checkit : function(element){
    if(event.target.className == "delete"){
        doSomethingweird();
    } else {
        doSomething();
    }
}

and the calling function looks something开发者_如何学Python like below.

<div onclick="ADDRESS.checkit(this);">
    <div class="delete">del</div>
</div>

Apparently, only input 'this' gets passed in, but I want to also pass in the event such that I can use it to find out the event.target.className. (Above code works in Chrome, but not in IE so far, because IE does not seem to recognize event) How should I change ADDRESS.addressbook_clicked(this); so that event also gets passed in?


Your HTML should be

<div onclick="ADDRESS.checkit(this, event||window.event);">
    <div class="delete">del</div>
</div>

Now the event element is also being passed to your event handler.

Warning This is old style event handling, most people nowadays use non-obtrusive event handling which decouples your JS and your HTML.


Bind your handler in the usual jQuery manner:

<div id="x">
    <div class="delete">del</div>
</div>

And:

$('#x').click(ADDRESS.checkit);

Then, change your ADDRESS to this:

var ADDRESS = {
    checkit : function(event){
        // And if you need your old "element", look in "this" instead.
        if(event.target.className == "delete"){
            doSomethingweird();
        } else {
            doSomething();
        }
    }
};

That should solve your cross-browser problems and it is the standard jQuery approach.


If you can garantee the structure of your HTML then you could do something like this:

var ADDRESS = {
    checkit : function(element){
    if($(this).children(".delete").length > 0){
        doSomethingweird();
    } else {
        doSomething();
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜