【问题标题】:jQuery + HTML : Using a or buttonjQuery + HTML:使用或按钮
【发布时间】:2013-09-29 08:40:53
【问题描述】:

大家早上好,

我实际上开始使用 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 脚本中的 链接。

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

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

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

所以,我想知道是否更可取(以优化和语义正确的方式)是使用

提前谢谢你

【问题讨论】:

    标签: jquery html optimization semantics preventdefault


    【解决方案1】:

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

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

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

    【讨论】:

    • 我想展示一个灯箱。 a标签是正确的还是我必须使用按钮标签?
    • 我真的必须使用 preventDefault 作为按钮标签吗?
    • AFAIK 您可以同时使用 abutton - 为此目的。如果您确实使用按钮标签,您实际上可以删除 preventDefault-code。
    猜你喜欢
    • 2017-08-16
    • 2016-12-28
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    相关资源
    最近更新 更多