javascript - jQuery 类事件处理程序 - 如何禁用类中的一个元素

标签 javascript jquery class event-handling stoppropagation

我有一个附加到类的事件处理程序,如下所示:

$('#container').on('click', '.myClass', function (e) {...

在此处理程序中,我想将不同的单击处理程序附加到已单击的元素。单击临时处理程序后,我想重新启用原始处理程序。

我正在尝试做的(如此 fiddle 所示)是允许单击一段文本,将其更改为输入文本框,然后提交更改以重新创建文本。

我尝试了以下方法但没有成功,如 the fiddle 所示:

$('#container').on('click', '.submit', function (e) {
    var $this = $(this),
        new_text = $this.prev().val();
    e.stopPropagation();
    $this.parent().off('click.temp').html(new_text);                    
});

$('#container').on('click', '.test', function (e) {
    var $this = $(this);
    $this.html("<input type='text' value='" + $this.text() + "'/><input class='submit' value='Submit' type='submit'>");
    $this.on('click.temp', function (e) {
        e.stopPropagation();
    });
});

使用 .off() 似乎不会取消类上的原始处理程序,因为它附加到类而不是元素。

我想我已经用 e.stopPropagation() 部分地回答了我的问题,但它仍然不是很有效,我不相信我会以最好的方式解决这个问题:)

备注:This post与想法相关但不使用this

最佳答案

你可以像下面这样简单地做到这一点:

function testClick() {

    var $this = $(this),
        text = $this.text();

    // you have to off the click like this
    $('#container').off('click', '.test');
    
    $this.html(
        "<input class='text' type='text' value='" + text + "'/><input class='submit' value='Submit' type='submit'>"
    );

    $this.find('.submit').on('click', function(e) {
        e.stopPropagation();
        var new_text = $this.find('input.text').val();
        $this.html(new_text);
        $('#container').on('click', '.test', testClick); // again on click
    });
}

$('#container').on('click', '.test', testClick);

Working sample

您可以像下面这样分隔提交事件:

function testClick() {

    var $this = $(this),
        text = $this.text();

    // you have to off the click like this
    $('#container').off('click', '.test');

    $this.html("<input class='text' type='text' value='" + text + "'/><input class='submit' value='Submit' type='submit'>");
}

$('#container').on('click', '.submit', function(e) {
    e.stopPropagation();
    var new_text = $(this).prev('input.text').val();
    $(this).parent().html(new_text);
    $('#container').on('click', '.test', testClick); // again on click
});

$('#container').on('click', '.test', testClick);

Working sample

关于javascript - jQuery 类事件处理程序 - 如何禁用类中的一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11445172/

相关文章:

javascript - 我们可以将 $(this) 与其他选择器一起使用吗?

IE8 中的 jQuery "Exception thrown and not caught"错误

c++ - 对象如何将自身添加到该对象的类中的 vector ?

c++ - 公开定义对象,但在构造函数中创建它

c++ - 当 stream.peek()= ='\n' 时,stream >> z1 有什么用

javascript - Select 使用 or 语句更改 div 状态

javascript - 正则表达式,搜索多个换行符

javascript - javascript中对象键的大小

javascript - 仅将 boostrap bootstrap.min.css 文件应用于一个 div 或像 datetimepicker 这样的控件?如何

javascript - Facebook 请求对话框不会停止在实时服务器中加载