jquery函数用于同一类的多个按钮事件
jquery function for multiple button event with same class
$(document).ready(function() {
$(".like").click(function() {
var newValue = parseInt($(".no-like").text()) + 1;
alert(newValue);
$(".no-like").html(newValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="like" data-creation-id="1069347886434951" data-id="1" href="#">
<span class="no-like">35</span>
</a>
<a class="like" data-creation-id="1069347886434951" data-id="1">
<span class="no-like">3</span>
<span class="glyphicon glyphicon-heart"></span>
</a>
<a href="">hey</a>
这里有多个按钮。每次单击它时,您需要添加1个值。例如:35到36和3到4。Jquery必须选择每个具有相应值的按钮。但即使是一个按钮,代码也不起作用。
只需使用'this'关键字来引用元素的当前实例
$(document).ready(function() {
$(".like").click(function() {
var newValue = +$(this).text() + 1;
if($(this).find('.no-like').length)
$(this).find('.no-like:eq(0)').text(newValue);
else
$(this).text(newValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="like" data-creation-id="1069347886434951" data-id="1" href="#">
35
</a>
<a class="like" data-creation-id="1069347886434951" data-id="1">
<span class="no-like">3</span>
<span class="glyphicon glyphicon-heart"></span>
</a>
$(document).ready(function() {
$(".like").click(function() {
var newValue = parseInt($(this).text()) + 1;//use this context for clicked element
alert(newValue);
$(".no-like").html(newValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="like" data-creation-id="1069347886434951" data-id="1" href="#">
35
</a>
<a class="like" data-creation-id="1069347886434951" data-id="1">
<span class="no-like">3</span>
<span class="glyphicon glyphicon-heart"></span>
</a>
<a href="">hey</a>
使用此上下文
您必须使用$(this)
从同一元素获取。
$(document).ready(function() {
$(".like").click(function() {
var newValue = parseInt($(this).text()) + 1;
alert(newValue);
$(".no-like").html(newValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<a class="like" data-creation-id="1069347886434951" data-id="1" href="#">
35
</a>
<a class="like" data-creation-id="1069347886434951" data-id="1">
<span class="no-like">3</span>
<span class="glyphicon glyphicon-heart"></span>
</a>
<a href="">hey</a>
相关文章:
- 分派点击事件并保留击键修饰符
- 模糊事件的Javascript测试
- keyup事件处理程序更改焦点不适用于快速键入
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 如何使Javascript动态html表及其上的事件
- 使用类从一个标记中双击事件
- 如何在未直接触发的情况下停止事件
- 如何在elfinder插件(一个文件管理器插件)上获得上传前事件
- 对iPad上的点击事件反应缓慢
- 事件和状态
- Fancybox是否将Click事件静音
- 主干-不管怎样,检查事件以前是否绑定过
- 从控制器返回后Ajax启动事件激发
- React-具有参数的同一类中的事件
- 在同一类 JQUERY 的不同时间触发事件
- 当我将事件添加到同一类差异 ID 时会出现一些错误
- 如何使用javascript onclick事件处理程序同一类锚元素
- jquery函数用于同一类的多个按钮事件
- 同一类的多个实例上的事件处理 - 需要澄清
- 为什么在同一类中触发点击事件时不触发更改事件