2017-04-03 9 views
0

jqueryを使用してクリックを追加してクリックしてIDの削除を試みています。jqueryを使用してクリックしてどこからでもidを追加して削除する方法

ここでは1つの質問があります。

私の機能を追加してもうまくいきますが、ユーザが.clickボタンを押さずにクリックした場合でも、idは.add divクラスから削除する必要があります。

私はこれを作成しましたDEMO codepen.ioから作成しました。どうすればいいですか、誰でもここで私を助けることができますか?それとも、他の方法がありますか?

ありがとうございます。あなたは緑色のボックスの外側をクリックしたときに

<div class="container"> 
    <div class="click" data-id="1">Click HERE</div> 

    <div class="add">Check</div> 
</div> 

JS

$(document).ready(function() { 
    $("body").on("click", ".click", function() { 
     var ID = $(this).attr("data-id"); 
     $(".add").attr('id', ID); 
     // When you click anywhere i want to remove added 
     // $(".add").attr('id', ID); 
     // Like this $(".add").attr('id', ''); 
    }); 
}); 
+0

からIDを削除しますあなたに役立つかもしれません –

答えて

1

これを試してみてください、それは、私の解決策を試してみてください.addクラス

$(document).ready(function() { 
 
    $("body").on("click", ".click", function() { 
 
     var ID = $(this).attr("data-id"); 
 
     $(".add").attr('id', ID); 
 
     // When you click anywhere i want to remove added 
 
     // $(".add").attr('id', ID); 
 
     // Like this $(".add").attr('id', ''); 
 
    }); 
 
}); 
 

 
$(document).mouseup(function (e) 
 
{ 
 
    var container = $(".container"); 
 

 
    if (!container.is(e.target) // if the target of the click isn't the container... 
 
     && container.has(e.target).length === 0) // ... nor a descendant of the container 
 
    { 
 
     $(".add").attr('id', ''); 
 
    } 
 
});
.container { 
 
    position:relative; 
 
    width:100%; 
 
    max-width:300px; 
 
    margin:0px auto; 
 
    padding:25px; 
 
    background:green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <div class="click" data-id="1">Click HERE</div> 
 
    
 
    <div class="add">Check</div> 
 
</div>

+0

'$( '。add')を使うこともできます。removeAttr ( 'id') 'id属性を削除します。 –

+0

ええ@PavelKozlov、質問は主に外部のクリックを見つけることです。 –

+0

@GaneshPuttaはあなたの答えに感謝します。それは私の答えのように見える。 – Azzo

関連する問題