[英]How do you make a click event for an entire class of buttons? jquery
<div id="tipboard"> <!--TIPS WILL POPULATE HERE--> <li>This is my fully informed tip about the environment and saving puppies<button class="btnLike" type="button" id="1"></button> </li> <li>This is a tip!<button class="btnLike" type="button" id="2"></button> </li> </div>
$(".btnLike").click(function () { console.log(this); addLike(this); });
var addLike = function (likeButton) { var idToShow = $(likeButton).attr("id"); console.log(idToShow); };
I'm am not getting anything logging to the console.我没有将任何内容记录到控制台。 How do I select the current button from a click event using the jquery class selector?
如何使用 jquery class 选择器从点击事件中 select 当前按钮?
Your code looks right.您的代码看起来正确。
The only potential cause could be:唯一的潜在原因可能是:
$
defined for something else, thus not showing any error logs about $
not being defined. $
,因此没有显示有关$
未定义的任何错误日志。 The first cause is highly unlikely so I suggest you try to run all your code after DOM is ready.第一个原因不太可能,所以我建议您在 DOM 准备好后尝试运行所有代码。
If you're not sure how to do it:如果您不确定如何操作:
$(document).ready(function () {
// Add your event handler and all other stuff here...
});
Your snippet isn't working because you haven't imported JQuery.您的代码段不起作用,因为您尚未导入 JQuery。 - Run the snippet below to see it work.
- 运行下面的代码片段以查看它的工作原理。
$(".btnLike").click(function () { console.log(this); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="tipboard"> <!--TIPS WILL POPULATE HERE--> <li>This is my fully informed tip about the environment and saving puppies<button class="btnLike" type="button" id="1"></button> </li> <li>This is a tip!<button class="btnLike" type="button" id="2">Click Here</button> </li> </div>
Additionally, if you want to ensure the DOM has loaded before your function runs you can declare the function like this:此外,如果您想确保在 function 运行之前已加载 DOM,您可以像这样声明 function:
$(document).on("click", ".btnLike", function () {
console.log(this);
});
I ended up just calling the function from the generated s with onClick.我最终只用 onClick 从生成的 s 中调用 function。
<li>${tip_message}<button class='btnLike' id=${tip_id} onClick='addLike(this, ${tip_likes})'></button>${tip_likes}</li>`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.