我的按钮的 jQuery 事件处理程序只工作一次
my jquery event handler for a button only works once
我正在制作一个像Twitter这样的社交网络网站。当用户想要编辑帖子时,我会打开一个div,使用jquery附加一个文本区域,一个"保存"按钮和一个"取消"按钮。
但是取消按钮只能工作一次,用户第二次单击编辑帖子时,取消按钮不再起作用。
$(function()
{
function edit(chirp_id)
{
var div1 = $('<div></div>');
div1.addClass('thumb2');
div1.attr('id', chirp_id);
$(div1).css('display','none');
if($(div1).is(':visible'))
{
return;
}
else
{
// Before the 'cancel' button I append the textarea and 'save' button
var cancel = $('<button></button>');
cancel.attr("id","cancelEdit");
cancel.text("Cancel");
cancel.addClass('button');
cancel.appendTo(div2);
$('#cancelEdit').click(function()
{
$(div1).fadeOut("slow");
});
}
my_edit = edit;
});
我用javascript调用我的函数
function edit_chirp(chirp_id)
{
my_edit(chirp_id);
}
试试这个 .. 用 dom 而不是 ID 绑定事件 ..
$(function () {
function edit(chirp_id) {
var div1 = $('<div></div>');
div1.addClass('thumb2');
div1.attr('id', chirp_id);
$(div1).css('display', 'none');
if ($(div1).is(':visible')) {
return;
} else {
//Before the 'cancel' button I append the textarea and the 'save' button
var cancel = $('<button></button>');
cancel.attr("id", "cancelEdit");
cancel.text("Cancel");
cancel.addClass('button');
cancel.appendTo(div2);
cancel.click(function () {
$(div1).fadeOut("slow");
});
}
my_edit = edit;
});
更好地使用delegates
使用.on
事件处理程序,因为div1 是动态创建的
$(document).on('click', '#cancelEdit', function () {
$(div1).fadeOut("slow");
});
缺少关闭edit
功能
可能
与闭包有关。 尝试:
cancel.click(function (event) {
$(event.target).closest(".thumb2").fadeOut("slow");
});
相关文章:
- Jquery FadeIn FadeOut 只工作一次
- jQuery滚动功能只工作一次
- iOS鼠标中心绑定只工作一次
- mongoose.js Model.remove在循环中只能工作一次
- 复选框一次选中一个不在gridview中工作
- Regex拆分-工作一次
- EventListener只能工作一次
- jQuery animate只在单击时工作一次
- data th JS每页只工作一次
- Jquery选择选项并获取只工作一次的更改值(页面加载时)
- remove仅每隔一次进行儿童工作
- CSS 类在验证时只工作一次
- Chrome扩展程序:浏览器操作单击按钮工作一次
- 单击仅工作一次
- MVC 分部视图中的 JQuery UI 自动完成功能只能工作一次
- Yelp API、OAuth和Angular与JSONP只工作一次
- 为什么这个脚本只工作一次?只替换元素一次,然后再也不替换
- 滚动时加载更多 滚动速度时一次工作两次
- 为什么一个ng应用程序一次工作
- Ajax请求只在每隔一次工作