jQuery makes it simpler:

$("#msg_button").bind("click", show_msg);

Or, if you are not reusing the function:

$("#msg_button").click( function() {
   alert('Nice to show you this');
});

-- Josh


----- Original Message ----- From: "Jquery-Newbe" <[EMAIL PROTECTED]>
To: "jQuery (English)" <jquery-en@googlegroups.com>
Sent: Tuesday, October 28, 2008 8:07 AM
Subject: [jQuery] Problem with adding EventListener



Hi, I have just started using JQuery. And so far, I have gotten some
problems with adding  events in the loading stage to a button.

The following is my code

<head>
<script src='js/jquery.min.js'></script>
<script type='text/javascript'>
$(function(){
$("#msg_button")[0].addEventListener('click',show_msg,false)
});

function show_msg()
{
alert("Nice to show you this")
}
</script>
</head>

<body>
<div id='msg'></div>
<button id='msg_button' name='msg_button' >Show Message</button>
</body>


So Here are my problems

Problem 1
$("#msg_button")[0].addEventListener('click',show_msg,false) doesn't
work in IE. It give me an error message saying that "This object
doesn't support the property or method ". I think I know the reason
for this. But I thought addEventListener method should be cross
platform in Jquery.

Problem 2
When I change $("#msg_button")[0] to $("#msg_button") instead, and it
gives me an error in both IE and Firefox saying "$
("#msg_button").addEventListener is not a function". After a deeper
inspection,   I found out that $("#msg_button") only returns an Object
object , where $("#msg_button")[0] returns object HTMLButtonElement
which is identical to what  document.getElementById returns. Should $
("#msg_button") return a proper object like Button, Link and so on
instead of a general Object? And also I am not sure if Javacript
support dereferencing as Java does.

So I come up a solution :

I put

function addEvent(obj,type,fn) {
if (obj.addEventListener) //in Mozila
{
obj.addEventListener(type,fn,false);
return true;
}
else // in IE
{
obj.attachEvent("on"+type,fn)
}
}

in my javascript block.

and replace $("#msg_button").addEventListener('click',show_msg,false)
with addEvent($("#msg_button")[0],'click',show_msg). And everything
work fine.


But my concern is this I though I can do all these common things in
Jquery way without introducing any of my self-defined functions!!!

Please Open my eyes to Jquery World.

Thank you very much.










Reply via email to