簡體   English   中英

如何獲得目標的父母

[英]how to get the target's parent

我該如何進行這項工作。

如果目標的父對象是.form_contact_div,則console.log('保持打開的表單');

我正在使用的代碼,但不適用於(否則if)條件,僅適用於if和else。

碼:

jQuery("body").click(function(e) {

    var target = jQuery(e.target);
    console.log(target);

    if(jQuery(target).parents('#contact-btn-div').length 
      && jQuery('#contact-btn-div').hasClass('close')) {
        console.log('keep open btn');
        jQuery("#form_contact_wrapper").animate({'left': '0px'});
        jQuery("#contact-btn-div").removeClass('close');
    }
    else if(jQuery(target).parent().is('.form_contact_div')) {
        console.log('keep open form');
        jQuery("#form_contact_wrapper").animate({'left': '0px'});
    }
    else{
        console.log('keep close');
        jQuery("#form_contact_wrapper").animate({'left': '-472px'});
        jQuery("#contact-btn-div").addClass('close');
    }
});

嘗試與類似e.taget更換

var target = $(this);

因為您需要將clicked元素作為標記,所以最好使用它,並且您的代碼應該像這樣

jQuery("body").click(function(e) {

    var target = $(this);
    console.log(target);

    if(target.parent('#contact-btn-div').length 
      && jQuery('#contact-btn-div').hasClass('close')) {
        console.log('keep open btn');
        jQuery("#form_contact_wrapper").animate({'left': '0px'});
        jQuery("#contact-btn-div").removeClass('close');
    }
    else if(target.parent().is('.form_contact_div')) {
        console.log('keep open form');
        jQuery("#form_contact_wrapper").animate({'left': '0px'});
    }
    else{
        console.log('keep close');
        jQuery("#form_contact_wrapper").animate({'left': '-472px'});
        jQuery("#contact-btn-div").addClass('close');
   }
});

檢查已編輯的代碼。

<div id="contact-btn-div" class="close" style="width:300px; height:200px; border:1px solid #666; background-color:#F60;">

<div style="width:200px; height:100px; border:1px solid #0FC; background-color:#9CC;"></div>
</div>

還有Javascript

$(function(){
$("body").click(function(e) {

var target = $(e.target);
console.log(target);

if(target.parent('#contact-btn-div').length 
  && $('#contact-btn-div').hasClass('close')) {
    console.log('keep open btn');
    $("#contact-btn-div").removeClass('close');
}

});
});

我認為您會得到所需的東西。 干杯:)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM