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

jQuery UI Dialog的open选项中$(this)未定义的问题求助

解决jQuery UI Dialog闭包中$(this)无效的问题

核心原因是Dialog的open回调函数里,this指向的是Dialog容器本身,而非点击的触发按钮,所以$(this).html()无法获取按钮文本,进而导致后续读取length时抛出错误。

两种可行的解决方法:

方法一:提前传递按钮文本到闭包

在绑定按钮点击事件时,先获取当前按钮的文本,作为参数传入filterWords函数,让闭包直接使用这个预存的参数:

// 修改过滤函数,接收按钮文本作为参数
function filterWords(filterText) {
  return function() {
    const filteredWords = gameDictionary.filter(word => word.startsWith(filterText));
    $('#dialog-content').html(filteredWords.join('<br>'));
  };
}

// 绑定按钮事件时传入按钮文本
$('.filter-btn').on('click', function() {
  const btnText = $(this).html();
  $('#word-dialog').dialog({
    open: filterWords(btnText),
    width: 300,
    modal: true
  });
});

方法二:通过Dialog选项存储触发元素

给Dialog添加自定义选项存储触发按钮,在open回调中从该选项读取元素并获取过滤文本:

<!-- 给按钮添加data属性存储过滤标识 -->
<button class="filter-btn" data-filter="A">A开头单词</button>
<button class="filter-btn" data-filter="B">B开头单词</button>
function filterWords() {
  return function() {
    // 从Dialog的自定义选项中获取触发按钮
    const triggerBtn = $(this).dialog('option', 'trigger');
    const filterText = triggerBtn.data('filter');
    const filteredWords = gameDictionary.filter(word => word.startsWith(filterText));
    $('#dialog-content').html(filteredWords.join('<br>'));
  };
}

$('.filter-btn').on('click', function() {
  $('#word-dialog').dialog({
    trigger: $(this), // 存储触发按钮到Dialog选项
    open: filterWords(),
    width: 300,
    modal: true
  });
});

两种方法都能规避this指向错误的问题,第一种逻辑更简洁,推荐优先使用。

内容的提问来源于stack exchange,提问作者Alexander Farber

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 22:33:15