2

如果我创建一个带有按钮的模态内联......我希望能够在单击每个按钮时执行某个操作。但是,我无法抓住模态中生成的这些按钮。

有谁知道我怎样才能抓住这些?

$('.open-popup-link').magnificPopup({
    items: {
        type: 'inline',
        src: $('<div class="white-popup">\
                    <h4>Are you sure you were discharged for failing a drugs test?</h4>\
                    <p>You will not be able to change your answer once you have submitted these details.</p>\
                    <button id="test-popup-no">No, I\'ve made a mistake</button>\
                    <button id="test-popup-yes">Yes, I\'m sure</button>\
                    </div>')
    },
    type: 'inline',
    midClick: true
});

当每个按钮被点击时,我想根据其 ID 执行不同的操作。

如果可以的话请帮忙。我一直在为此苦苦挣扎。只是做一个标准的 jQuery 选择似乎不起作用。

谢谢,迈克尔。

4

2 回答 2

4

@Irvin 发布的代码是有效的,但在应用程序性能方面不是很好。我建议使用打开/关闭回调来绑定/取消绑定点击事件,例如:

$('.open-popup-link').magnificPopup({
    items: {
        type: 'inline',
        src: $('<div class="white-popup">\
                    <h4>Are you sure you were discharged for failing a drugs test?</h4>\
                    <p>You will not be able to change your answer once you have submitted these details.</p>\
                    <button id="test-popup-no">No, I\'ve made a mistake</button>\
                    <button id="test-popup-yes">Yes, I\'m sure</button>\
                    </div>')
    },
    type: 'inline',
    midClick: true,
    callbacks: {
        open: function() {
            this.content.on('click.mycustomevent', '#test-popup-no', function() { 
                alert('hello world');
            });
        }, 
        close: function() {
           this.content.off('click.mycustomevent');
        }
    }
});
于 2013-12-17T23:06:46.403 回答
2

您可以尝试使用事件委托与 jQuery 绑定单击处理程序on

当提供选择器时,事件处理程序被称为委托。当事件直接发生在绑定元素上时,不会调用处理程序,而只会调用与选择器匹配的后代(内部元素)。jQuery 将事件从事件目标冒泡到附加处理程序的元素(即,从最内到最外的元素),并为沿该路径匹配选择器的任何元素运行处理程序。

代码:

$('.open-popup-link').magnificPopup({
    items: {
        type: 'inline',
        src: $('<div class="white-popup">\
                    <h4>Are you sure you were discharged for failing a drugs test?</h4>\
                    <p>You will not be able to change your answer once you have submitted these details.</p>\
                    <button id="test-popup-no">No, I\'ve made a mistake</button>\
                    <button id="test-popup-yes">Yes, I\'m sure</button>\
                    </div>')
    },
    type: 'inline',
    midClick: true
});

$('body').on('click','#test-popup-no', function(){
    alert('Nope!');    
})

$('body').on('click','#test-popup-yes', function(){
    alert('Yes');    
})

演示:http: //jsfiddle.net/IrvinDominin/A9dQ7/

于 2013-12-17T10:17:07.470 回答