简体   繁体   English

jQuery函数只能在第一次单击时正常工作

[英]jquery function works correctly only on first click

I have this function 我有这个功能

$(".plusmenus1").on('click', function() {
    $('.plusmenus1 i').toggleClass("fa-plus fa-minus");
    $("#care_and_washing").toggleClass("collapsed_MB  ");
    changeHeight();
});
$(".plusmenus2").on('click', function() {
    $('.plusmenus2 i').toggleClass("fa-plus fa-minus");
});

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

function changeHeight() {
    var divHeight = $("#care_and_washing").height() + $("#demo").height();

    if (!$("#care_and_washing").hasClass("collapsed_MB")) {
        $('#careheight').css('height', divHeight + 'px');
    } else {
        $('#careheight').css('height', '10px');
    }
}

it works but it gets the var divHeight = $("#care_and_washing").height() + $("#demo").height(); 它可以正常工作,但会得到var divHeight = $("#care_and_washing").height() + $("#demo").height(); correctly only on the first click after that it gets the var without the + so it adds the height only of the #care_and_washing 只有在第一次单击后才能正确获得var而没有+,因此它仅增加#care_and_washingheight

HTML (I'll try to add only what's needed) HTML(我将尝试仅添加所需的内容)

<div class="plusmenus1"><i data-toggle="collapse" data-target="#demo" style="float: left; position: relative; top: 3px; padding-right: 5px; color: black; font-size: 10px;" class="fa fa-plus collapsed" aria-hidden="true"></i>
<p id="care_and_washing" data-toggle="collapse" data-target="#demo" class="collapsed collapsed_MB" style="font-family: 'NiveauGroteskMedium'; font-size: 11px; color: black;">Care & Washing</p>
</div>
<div style="cursor: default; padding-left: 13px;" id="demo" class="collapse">
<p style="font-family: Questrial, sans-serif; font-size: 10px;">• Dry Flat</p>
<p style="font-family: Questrial, sans-serif; font-size: 10px;">• Do Not Bleach</p>
<p style="font-family: Questrial, sans-serif; font-size: 10px;">• Tumble Dry Low</p>
<p style="font-family: Questrial, sans-serif; font-size: 10px;">• Iron Low</p>
<p style="font-family: Questrial, sans-serif; font-size: 10px;">• Hand Wash</p>
</div>

<div id="careheight" ></div>

Hidden_Element.height() and Hidden_Element.width() will be 0 so you need to show to get height and hide again like this Hidden_Element.height()Hidden_Element.width()将为0因此您需要显示以获取高度并再次隐藏

function changeHeight() {
  var care_h = $("#care_and_washing").height();
  var demo_h = $("#demo").height();

  demo_h = demo_h == 0 ? $("#demo").show().height() : demo_h;

  $("#demo").hide();

  var divHeight = care_h + demo_h;

  if (!$("#care_and_washing").hasClass("collapsed_MB")) {
    $('#careheight').css('height', divHeight + 'px');
  } else {
    $('#careheight').css('height', '10px');
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM