在正确定义元素时,undefined的style.display

时间:2016-02-12 07:32:57

标签: javascript jquery

JSFiddle Demo

function toggleFoo() {
    var btn = $('button');

    btn.click(function () {
        var thisElem = $(this).closest('.parent').find('.children');
        console.log(thisElem.length)
        thisElem.style.display = (thisElem.style.display == 'none') ? 'block' : 'none';
    });
};

$(document).ready(function() {
    toggleFoo();
});

为什么我在尝试访问正确定义的元素undefined以及可以访问哪个style.display时获得length

3 个答案:

答案 0 :(得分:3)

thisElemjQuery object,不是dom element引用,因此它没有style属性。

如果您只想切换元素的显示,那么您只需使用jQuery中的.toggle()方法。



function toggleFoo() {
  var btn = $('button');

  btn.click(function() {
    var thisElem = $(this).closest('.parent').find('.children');
    console.log(thisElem.length)
    thisElem.toggle();
  });
};

$(document).ready(toggleFoo);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <button>Click me</button>
  <div class="children">
    <h2>foo</h2>
  </div>
</div>
&#13;
&#13;
&#13;

如果你想访问dom元素,那么你可以说

var thisElem = $(this).closest('.parent').find('.children')[0];

答案 1 :(得分:0)

请尝试输出:

function toggleFoo() {
    var btn = $('button');

    btn.click(function () {
        var thisElem = $(this).closest('.parent').find('.children');
        var display = (thisElem.css("display") == 'none') ? 'block' : 'none';
        thisElem.css("display",display);
    });
};

$(document).ready(function() {
    toggleFoo();
});

答案 2 :(得分:0)

您需要访问dom才能获得style属性。

使用$(this).closest('.parent').find('.children');时,结果将包含在jQuery对象中。要获取dom元素,请添加要定位的元素的键索引。例如在你的情况下[0]

因此:

var thisElem = $(this).closest('.parent').find('.children')[0];

相关问题