"click" event handler not firing
I have a php page that print开发者_运维百科s out a div having multiple anchor tags with different IDs. Here is a sample code:
echo "<div id=\"pageLinks\">";
echo " <a href=\"javascript:;\" id=\"1\"><<</a> ";
echo "another link...."
echo "</div">;
The javascript code that should listen for the click
event is the following:
$(document).ready(function(){
$("div#pageLinks a").click(function(){
alert("clicked");
});
});
but it's apparently not working (I cannot see the "clicked" alert). Can someone help me?
Your HTML source code is totally broken. You should use <
instead of <
and close your last div properly.
Your javascript code btw is working, check it here: http://jsfiddle.net/raszi/H9dnE/3/
UPDATE
A possible better code:
PHP:
echo '<div id="pageLinks">';
echo '<a href="#" id="1"><<</a>'
echo 'another link...';
echo '</div>';
Javascript:
$(function() {
$("div#pageLinks a").click(function( event ) {
event.stopPropagation();
alert("Clicked!");
});
});
Can be checked here: http://jsfiddle.net/raszi/p3Ug2/
Rewrite your code this way:
echo "<div id=\"pageLinks\">";
echo " <a id=\"1\"><<</a> ";
echo "another link...."
echo "</div>";
And then
$(document).ready(function(){
$("div#pageLinks a").click(function(){
alert("clicked");
});
});
should work. Do not put wrong HTML code in the page! And use HTML entities (<
, >
) instead of <
and >
Look at the html source code. Probably you can see it's messed up somehow. Maybe it helps also I you use echo with single quotest...in any case you don't have to escape the double quotes anymore and your codes gets more readable.
精彩评论