简体   繁体   中英

JQuery dialog close

I'm facing a problem with dialog closing in JQuery

Here's the code I have :

  $(window).on("click",function(e){ if($(e.target).not("#test")){ $("#test").hide(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <dialog open id="test"></dialog> <input type="submit" onclick="$('#test').show()"> 

Well, function works like it supposed to(closes dialog when I click outside of it's content) but then I can't toggle it again. Because of the function, I suppose.

Also I tried to fix it with such way but it don't work either :

 if($("#test").css("display","block")){ $(window).on("click",function(e){ if($(e.target).not("#test")){ $("#test").hide(); } }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <dialog open id="test"></dialog> <input type="submit" onclick="$('#test').show()"> 

Is there any way to fix this?

That you very much for spending your precious time with my problem!

Thank you very much for any help or advice!

Your submit click event fires first and then the window click event fires. Hence your dialog keeps getting hidden. Ensure you are not propagating the click event from your submit button if you want to show the dialog.

You might want to add validation to ensure your dialog is not already open when clicking submit though.

 $(window).on("click", function(e) { console.log('window click'); if ($(e.target).not("#test")) { $("#test").hide(); } }); $('input[type=submit]').on('click', function(){ $('#test').show(); event.stopPropagation(); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <dialog open id="test"></dialog> <input type="submit" onclick=""> 

You don't need show or hide functions, you just need to use the open property and change it to false or true.

  $(window).on("click",function(e){ if($(e.target).not("#test") && !$(e.target).is("#submit")){ $("#test")[0].open = false; // or document.getElementById("test").open = false; } }); $('#submit').click(function() { $('#test')[0].open = true; // // or document.getElementById("test").open = true; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <dialog open id="test"></dialog> <input type="submit" id="submit"> 

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