admin管理员组

文章数量:1405112

Relevant bootstrap.js code:

...
Dropdown.prototype = {

  constructor: Dropdown

  , toggle: function (e) {
     var $this = $(this)
     , $parent
     , isActive

  $parent = getParent($this)

  isActive = $parent.hasClass('open')
  ....

Is there a way to check for an open dropdown using isActive in a oneliner jquery like:

if($('#dropdownElement').isActive) 

I know I can do something like:

var parent = $('#aParentID');
if(parent.hasClass('open')) { ...

But I wonder if I'm able to do it that way, thanks.

Relevant bootstrap.js code:

...
Dropdown.prototype = {

  constructor: Dropdown

  , toggle: function (e) {
     var $this = $(this)
     , $parent
     , isActive

  $parent = getParent($this)

  isActive = $parent.hasClass('open')
  ....

Is there a way to check for an open dropdown using isActive in a oneliner jquery like:

if($('#dropdownElement').isActive) 

I know I can do something like:

var parent = $('#aParentID');
if(parent.hasClass('open')) { ...

But I wonder if I'm able to do it that way, thanks.

Share Improve this question asked Jul 10, 2013 at 2:36 Antonio MaxAntonio Max 8,8337 gold badges44 silver badges43 bronze badges 2
  • 2 you can write is as a plugin, if you want – Arun P Johny Commented Jul 10, 2013 at 2:37
  • 2 There's is too: if ($('#parent').is('.open')) – elclanrs Commented Jul 10, 2013 at 2:38
Add a ment  | 

2 Answers 2

Reset to default 3

If you need a one liner, then write it as a plugin

(function($){
    $.fn.isActive = function(){
        console.log(this)
        return $(this.get(0)).hasClass('open')
    }
})(jQuery)

Then

$('#dropdownElement').isActive()

Demo: Fiddle

The accepted solution did not work for me. I was using Bootstrap 4, maybe something has changed. I digged into dropdown.js code and I found this:

const ClassName = {
  ...
  SHOW      : 'show',
  ...
}
...
toggle() {
   ...
   const isActive = $(this._menu).hasClass(ClassName.SHOW)
   ...
}

So the solution for me was:

var isShown = document.getElementById('dropdownElement').classList.contains('show');

Using jQuery, that'd be:

var isShown = $("#dropdownElement").hasClass("show");

本文标签: javascriptDropdownCheck if open using quotisActivequot propertyStack Overflow