Klaus Hartl wrote:
plewas wrote:
Helllo
I have code like this:
[code]
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript">
<!--
$(function(){
$("#b").click( function() {
$("h2").append('<a href="#" id="a">hellooooo</a>');
} );
$("#a").click( function() {
alert("aaaaa");
} );
});
//-->
</script>
</head>
<body>
<div><h1 ><a href="#" id="b">hello1</a></h1><h2>xxx</h2><a href="#"
id="a">hello2</a></div>
</body>
</html>
[/code]
Why, when i click link id =a (hello2) from body document, alert is
appired on screen, but when i click link id=a (heloooo) which was
appened by $("#b").click( function() (hello1) allert is not apper?
Any solution?
Best reagards
plewas
At the time you try to add the click listener to #a, that element
doesn't exist yet in the DOM tree. You need to add the listener after
you've added that element to the document.
Try:
$(function(){
$('#b').click(function() {
$('<a href="#">hellooooo</a>')
.appendTo('h2')
.click(function() {
alert("aaaaa");
});
});
});
--Klaus
Apart from that, do not use duplicate ids. If you have two identical ids
in a document, the query $('#duplicate') will return only the first
match (due to usage of document.getElementById behind the scenes) and it
is invalid HTML anyway.
And speaking of HTML, unless you serving XHTML as XML you shouldn't use
an xml declaration. That's simply wrong and gives you more trouble
because its putting IE into Quirks mode.
--Klaus