onchange 找到这个父级

发布于 2024-09-11 22:39:32 字数 418 浏览 1 评论 0原文

我有几个具有以下结构的选择框(至少 5 个)

<li>
   <div>
      <select name="sb[]">...</select>
   </div>
</li>

当 sb 更改时,我想要进行 ajax 调用,传递所选值并用从 ajax 接收的 html 替换父 li 的内容。

我尝试了以下方法

onchange="
    $.get('file.php', { action: 'dothis'}, function(html) { 
      $(this).parent('li').html(html);
    });
"

,但不起作用

任何帮助

I have a few select boxes (at least 5) with the following structure

<li>
   <div>
      <select name="sb[]">...</select>
   </div>
</li>

When a sb change i want to make an ajax call pass the selected value and replace the content of parent li with the html receive from ajax.

I tried the following

onchange="
    $.get('file.php', { action: 'dothis'}, function(html) { 
      $(this).parent('li').html(html);
    });
"

but is not working

Any Help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

荒路情人 2024-09-18 22:39:32
$('select[name="sb[]"]').change(function(){
   var $this = $(this);
   $.get('file.php', { action: 'dothis'}, function(html) { 
      $this.closest('li').html(html);
    });
})
$('select[name="sb[]"]').change(function(){
   var $this = $(this);
   $.get('file.php', { action: 'dothis'}, function(html) { 
      $this.closest('li').html(html);
    });
})
金兰素衣 2024-09-18 22:39:32

如果您真的非常愿意,您仍然可以在 onchange 属性中执行此操作。问题是(正如所指出的)双重的:首先,ajax回调中的this与change事件处理程序中的this不再相同,其次你应该使用closest()或parents():

onchange="
    var select = $(this);
    $.get('file.php', { action: 'dothis'}, function(html) { 
      select.closest('li').html(html);
    });
"

onchange="
    $.get('file.php', { action: 'dothis'}, $.proxy(function(html) { 
      $(this).closest('li').html(html);
    }, this));
"

If you really, really want to, you could still do this in the onchange attribute. The problem is (as pointed out) twofold: firstly, the this inside the ajax callback is not the same this anymore as in the change event handler, secondly you should be using closest() or parents():

onchange="
    var select = $(this);
    $.get('file.php', { action: 'dothis'}, function(html) { 
      select.closest('li').html(html);
    });
"

or

onchange="
    $.get('file.php', { action: 'dothis'}, $.proxy(function(html) { 
      $(this).closest('li').html(html);
    }, this));
"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文