on() 无法识别类
on() doesn't recognize a class
我遇到了on()
的问题。这是我的代码:
<span class="add" id="id_foo" >add this stuff</span>
$(".add").on('click', function() {
$.post("/toto.com/add.php", { trainning: this.id }, function() {});
$(this).html("Remove this stuff");
$(this).removeClass("add").addClass("remove");
//alert($(this).attr("class"));-->give the good class
});
$(".remove").on('click', function() {
//doesn't work
$.post("/toto.com/remove.php", { trainning: this.id }, function() {});
$(this).html("add this stuff");
$(this).removeClass("remove").addClass("add");
});
类remove
的选择器无法识别它,而当我单击带有add
类的按钮时,类正在更改。你知道问题是什么吗?
感谢您的帮助!
在动态更改处理程序附加到的类时,需要使用委托的事件处理程序。试试这个:
$(document).on('click', ".add", function() {
$.post("/toto.com/add.php", { trainning: this.id });
$(this).html("Remove this stuff").toggleClass("add remove");
});
$(document).on('click', ".remove", function() {
$.post("/toto.com/remove.php", { trainning: this.id });
$(this).html("add this stuff").toggleClass("remove add");
});
根据此 JS 代码所在的script
标记的位置,您可能还需要将代码包装在 document.ready 处理程序中。如果它就在</body>
标签之前,它将正常工作,如果它在头部,请将其放在$(function() { /* your code here */ });
相关文章:
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 如何识别我的网站中的慢速设备
- Google/html5语音识别JavaScript SDK Chrome网络工具包SpeechRecognition
- AngularJS指令只识别双向绑定类型
- I'我设计了一个下拉菜单,onclick会出现,而on blur会消失
- window.on.scroll事件未启动
- php脚本中无法识别ajax传递的值
- 识别没有ID或特定属性的对象
- JavaScript无法识别图像
- Socket.io on Mozilla Rhino
- CSS中的游标属性似乎不适用于USB On The Go
- jQuery点击ON现在使用.load触发关闭
- JQuery.on(“keydown”)追加到页面时不工作
- Angular JS/Rube-on-Rails-控制器未识别错误
- BackboneJS on Rails 语法错误,无法识别的表达式:/1
- 即使使用“on”,JQuery 也无法识别通过主干视图添加的元素
- 如何在ruby on rails中使用ajax识别单击了哪个图像
- 如何让jquery识别使用.on创建的动态元素?
- AngularJS: ui开关位置(ON/OFF)识别
- .on 或 .live 函数均无法识别