Aakash Goel
Aakash Goel

Reputation: 1179

"click" event handler not firing

I have a php page that prints 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?

Upvotes: 0

Views: 1203

Answers (3)

marzapower
marzapower

Reputation: 5611

Rewrite your code this way:

echo "<div id=\"pageLinks\">";
echo " <a id=\"1\">&lt;&lt;</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 (&lt;, &gt;) instead of < and >

Upvotes: 1

KARASZI Istv&#225;n
KARASZI Istv&#225;n

Reputation: 31477

Your HTML source code is totally broken. You should use &lt; 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">&lt;&lt;</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/

Upvotes: 2

Bas Slagter
Bas Slagter

Reputation: 9929

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.

Upvotes: 0

Related Questions