You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

类内部jQuery脚本问题:无法正确获取动态元素.ac-list

解决jQuery事件绑定中类实例与目标元素的上下文冲突问题

你遇到的核心问题是事件回调里的上下文被bind(this)改变了——你用.bind(this)把回调函数的this绑定成了filter类的实例,所以此时回调里的this不再是被点击的.ac-list元素,而是你的类对象,这时候把this赋值给this.clicked_ac_list自然拿不到想要的DOM元素。

修正方案:通过事件对象获取目标元素

jQuery的事件回调会自动传入event参数,你可以通过event.target拿到实际被点击的DOM元素,再转成jQuery对象即可。如果.ac-list内部还有子元素,建议用.closest('.ac-list')确保拿到正确的父元素,避免点击子元素时出错。

修正后的完整代码:

// 用于管理筛选的类(构造函数首字母大写是规范哦)
function Filter(){
    this.keyword = { word:"", matching:"" };// matching exact, prefix, infix
    this.category = "";
    this.filters = [ ];// an array of {key:"",value:""}
    this.ac_results = $( ".ac-container .ac-results" );
    this.ac_results.on( "click" , ".ac-list" , function( event ){
        // 修正:通过event.target获取点击的元素,并用closest确保拿到.ac-list
        this.clicked_ac_list = $( event.target ).closest('.ac-list');
        this.category = this.clicked_ac_list.attr( "data-category" );
        this.keyword.word = this.clicked_ac_list.attr( "data-keyword" );
        console.log( this.category );
        console.log( this.keyword );
    }.bind( this ) );
}
// 实例变量名不要和构造函数同名,避免变量覆盖
var filterInstance = new Filter();

补充说明:

  1. 为什么bind(this)会导致上下文变化?.bind(this)的作用是强制让回调函数里的this指向你的Filter类实例,这样你才能在回调里访问类的keyword、category等属性,但代价是丢失了原本的DOM元素上下文。
  2. 如果你不想用event.target,也可以在绑定事件前用变量保存类上下文,比如:
var self = this;
this.ac_results.on( "click" , ".ac-list" , function( ){
    var clickedAcList = $(this); // 这里的this是被点击的元素
    self.category = clickedAcList.attr( "data-category" );
    self.keyword.word = clickedAcList.attr( "data-keyword" );
});

这种方式不需要bind(this),而是用self指代类实例,this自然就是DOM元素,两种方案都能解决问题,看你习惯哪种写法。

内容的提问来源于stack exchange,提问作者Sami Al-Subhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:43:48