简体   繁体   中英

jQuery click anywhere except a div

I have the function below to add text to another input. when I click anywhere on the page I want to show an alert message furthermore when I click on texts I want to run the special function for them but, in all conditions, it considers $(document).click part. How can I define all part of my page except that specific div?

here is my code :

 function clicking(s) { $(s).closest(".search_div").find(".country").val($(s).find(".txtcountry").text()) $(s).closest(".search_div").find(".co-id").val($(s).find(".countryid").val()) $(s).closest(".search_div").find(".co").empty(); } $(document).click(function(event) { alert("hello") });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="search_div"> <input class="country" value="" type="text" /> <input type="hidden" class="co-id" value="" /> <div class="co" style="border:1px solid red;"> <div class="selectCountry" onClick="clicking(this)"> <input type="hidden" value="1198418" class="countryid" /> <span class="txtcountry"> <i class="fa fa-arrow-right"></i> Turkey-Ankara</span> </div> <div class="selectCountry" onClick="clicking(this)"> <input type="hidden" value="1198425" class="countryid" /> <span class="txtcountry"> <i class="fa fa-arrow-right"></i> Turkey-Istanbul</span> </div> </div> </div>

Simply return from function if event.target is the div . Try the following way:

 function clicking(s){ $(s).closest(".search_div").find(".country").val($(s).find(".txtcountry").text()) $(s).closest(".search_div").find(".co-id").val($(s).find(".countryid").val()) $(s).closest(".search_div").find(".co").empty(); } $(document).click(function(event) { if($(event.target).hasClass('country') || $(event.target).hasClass('co') || $(event.target).hasClass('txtcountry')) return; alert("hello") });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="search_div"> <input class="country" value="" type="text"/> <input type="hidden" class="co-id" value=""/> <div class="co" style="border:1px solid red;"> <div class="selectCountry" onClick="clicking(this)"> <input type="hidden" value="1198418" class="countryid"/> <span class="txtcountry"> <i class="fa fa-arrow-right"></i> Turkey-Ankara</span> </div> <div class="selectCountry" onClick="clicking(this)"> <input type="hidden" value="1198425" class="countryid"/> <span class="txtcountry"> <i class="fa fa-arrow-right"></i> Turkey-Istanbul</span> </div> </div> </div>

Make use of the .not() method:

 $(document).not('.selectCountry').on('click', function(e) { // Handle event gracefully e.preventDefault(); alert('Hello'); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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