委派的事件处理程序选择器

Delegated Event Handler Selector

本文关键字:选择器 程序 事件处理 委派      更新时间:2023-09-26

我正在尝试对动态加载的内容使用委托的事件处理程序,如下所示:

AjaxProt.prototype = {
    // bind handler - ensure to use $(document) to delay call to .on() method
    init: function () {
        var thisObj = this;
        $(document).on(thisObj.event, thisObj.targetEl, function (e) {
            e.preventDefault();
            var url = $(thisObj.targetEl).attr('href');
            thisObj.ajaxRequest(url);
        });
    },
    ajaxRequest: function (url) {
        var thisObj = this,
            method = this.method,
            ajaxCallType = this.ajaxCallType,
            callback;
        // $.ajax here

targetEl被分配给[id^=startOfClassName] .我尝试将href值从init()传递到ajaxRequest(),但它仍然只选择与页面上的选择器匹配的第一个元素。如何确保href值绑定到实际单击的元素?谢谢!

抱歉浪费时间,我自己想通了。

我所要做的就是将var url = $(thisObj.targetEl).attr('href')更改为var url = $(this).attr('href'),因为this现在在 thisObj.targetEl 的范围内,因此指向单击的特定元素。