0

大家早上好,

我实际上开始使用 jQuery 进行开发,并且我想以一种优化且语义正确的方式正确地进行开发。我写了一个简单的例子让你了解我的问题在哪里:

<?php 
$file = 'count.txt';
$count = file_get_contents($file);
$count = (int) $count + 1;
file_put_contents($file, $count);
?>
<html>
  <body>
    <p><?php echo $count; ?></p>
    <a href="" id="hello">Cliquez !</a>
  </body>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script>
    $('#hello').click(function(){
      $(this).hide();
    });
  </script>
</html>

php 脚本正在计算页面被加载并显示的次数。html 部分包含一个我想隐藏在 jQuery 脚本中的 < a > 链接。

上面的例子没有隐藏<a>,或者我们看不到它被隐藏了,因为浏览器在刷新页面之后立即刷新了页面,因为href是空的。因此,php 计数只是在增加,而 < a > 并没有被隐藏。

我用谷歌搜索了我的问题,发现我必须使用“return false;” 在我的脚本结束时停止事件传播到浏览器。好的,我知道了。

但是,实际上,“return false”;函数实际上包含 2 个函数:preventDefault() 和 stopPropagation()。看到这个http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

所以,我想知道是否更可取(以优化和语义正确的方式)是否使用 <button> 标签而不是 <a> 或继续使用 <a> 标签并替换 return false; 通过防止默认。

先感谢您

4

1 回答 1

1

您必须抑制单击时发生的默认事件,这样您就可以根据自己的(样式?)偏好选择eiter按钮或a-tag。如果它的语义正确也取决于上下文;)

<script>
    $('#hello').click(function(event){
        event.preventDefault();
        $(this).hide();
    });
</script>

另见:http ://www.w3schools.com/jquery/event_preventdefault.asp

于 2013-09-24T08:30:42.407 回答