计数器不起作用 - 在php中实现一个类似的按钮

问题描述 投票:0回答:1

我试图实现像按钮,当点击它应该增加喜欢的数量,但我试图在PHP代码内实现但它不工作,我不能弄清楚这里有什么问题?

<html>
<script>
$(".like_button button").on("click", function() {
  var $count = $(this).parent().find('.count');
  $count.html($count.html() * 1 + 1);
});
</script>
<?php
   echo '<div class="like_button">
  <button>Like</button>
  <span class="count">0</span>
</div>';
?>
</html>

为什么这段代码不起作用?

javascript php html echo
1个回答
2
投票

这是因为你在按钮存在之前就选择它了。把$(".like_button button")放在按钮后面:

<?php
   echo '<div class="like_button">
  <button>Like</button>
  <span class="count">0</span>
</div>';
?>

<script>
    $(".like_button button").on("click", function() {
        var $count = $(this).parent().find('.count');
         $count.html($count.html() * 1 + 1);
    });
</script>

编辑:

跟进你的评论,你没有包含jQuery,但你正在尝试使用它($)。然后解决方案很简单:包含jQuery。然后打开你的控制台。

工作片段:

$(".like_button button").on("click", function() {
  var $count = $(this).parent().find('.count');
  $count.html($count.html() * 1 + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="like_button">
  <button>Like</button>
  <span class="count">0</span>
</div>
<div class="like_button">
  <button>Like</button>
  <span class="count">0</span>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.