jQuery从中删除所选选项

问题描述 投票:29回答:4

第一篇文章在这里,我安静地来了:)我已经搜索过,但是找不到我想要的东西。

我试图操纵选择框的选定选项。有人可以解释为什么这有效:

$('#some_select_box').click(function() {
  $('#some_select_box option:selected').remove();
});

但这不是:

$('#some_select_box').click(function() {
  $('this option:selected').remove();
});

我只是想使用“this”而不是拼写出选择框的id - 有人能指出我正确的语法方向吗?这让我很生气,因为它看起来应该很简单。而且我确信这是给某人,但不是我,因为它结束了一天,我被大脑炸了......任何指针都非常赞赏。

干杯

jquery select this option selected
4个回答
55
投票

this不是css选择器。您可以通过将其作为上下文传递来避免拼写this的id:

$('option:selected', this).remove();

http://api.jquery.com/jQuery/


8
投票
 $('#some_select_box').click(function() {
     $(this).find('option:selected').remove();
 });

使用find方法。


5
投票

这应该做的伎俩:

$('#some_select_box').click(function() {
  $('option:selected', this ).remove();
});

3
投票

这是一个更简单的

$('#some_select_box').find('option:selected').remove().end();
© www.soinside.com 2019 - 2024. All rights reserved.