jQuery:在选择框中快速选择整个 optgroup 的简单方法

发布于 2024-09-13 20:16:33 字数 685 浏览 2 评论 0原文

我使用与此线程中的函数类似的 jQuery 函数: 在 select 中快速选择整个 optgroup 的简单方法 但是,当我单击

  $("optgroup").click(function(e) {
    $(this).children().attr('selected','selected');
  });

我的 HTML 看起来像这样:

<optgroup label="Abc">
<option value="8" >Ab</option> 
<option value="7" >C</option></optgroup>

因此,单击 也会选择 。也许我错过了一些明显的东西......

I use a jQuery function similar to the one in this thread:
Easy way to quick select a whole optgroup in select box

But, when I click an <option> now it selects the whole optgroup, as the optgroup encloses the option elements.
I use the following snippet:

  $("optgroup").click(function(e) {
    $(this).children().attr('selected','selected');
  });

my HTML looks like this:

<optgroup label="Abc">
<option value="8" >Ab</option> 
<option value="7" >C</option></optgroup>

So clickig on <option>C</option> selects <option>Ab</option> as well. Perhaps I am missing something obvious...

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

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

发布评论

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

评论(2

梨涡 2024-09-20 20:16:33

我可能是错的,但您可能需要向 添加一个处理程序以阻止点击事件冒泡。

像这样简单的事情可能会有所帮助:

$("optgroup option").click(function(e) {
    e.stopPropagation();
});

I could be wrong but you might need to add a handler to the <option>s to stop the click event bubbling up.

Something as simple as this might help:

$("optgroup option").click(function(e) {
    e.stopPropagation();
});
烂人 2024-09-20 20:16:33

另外,您可以检查 optgroup 点击处理程序中的目标,并短路事件的目标是否实际上是选项标签,如下所示:

$("optgroup").click(function(e) {
   if ($(e.target).is('option')) return;
   $(this).children().attr('selected','selected');
});

also, you could check the target in your optgroup click handler, and short-circut if the event's target is actually an option tag, like so:

$("optgroup").click(function(e) {
   if ($(e.target).is('option')) return;
   $(this).children().attr('selected','selected');
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文