简体   繁体   English

“单击”事件处理程序未触发

[英]“click” event handler not firing

I have a php page that prints out a div having multiple anchor tags with different IDs.我有一个 php 页面,该页面打印出一个具有多个具有不同 ID 的锚标记的 div。 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:应该监听click事件的 javascript 代码如下:

$(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.您的 HTML 源代码完全损坏。 You should use &lt;你应该使用&lt; instead of < and close your last div properly.而不是<并正确关闭你的最后一个 div 。

Your javascript code btw is working, check it here: http://jsfiddle.net/raszi/H9dnE/3/您的 javascript 代码 btw 正在运行,请在此处查看: http://jsfiddle.net/raszi/H9dnE/3/

UPDATE更新

A possible better code:一个可能更好的代码:

PHP: PHP:

echo '<div id="pageLinks">';
echo '<a href="#" id="1">&lt;&lt;</a>'
echo 'another link...';
echo '</div>';

Javascript: Javascript:

$(function() {
  $("div#pageLinks a").click(function( event ) {
    event.stopPropagation();

    alert("Clicked!");
  });
});

Can be checked here: http://jsfiddle.net/raszi/p3Ug2/可以在这里查看: http://jsfiddle.net/raszi/p3Ug2/

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!不要在页面中放错 HTML 代码! And use HTML entities ( &lt; , &gt; ) instead of < and >并使用 HTML 实体( &lt;&gt; )而不是<>

Look at the html source code.查看 html 源代码。 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.也许它也有助于我使用带有单引号的 echo ...在任何情况下,您都不必再转义双引号,并且您的代码变得更具可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM