如何通过JavaScript将元素的visibility:hidden设置为visible?
Fixing the Visibility Toggle Issue
Hey there! Let's fix that visibility toggle issue you're having. The problem comes down to a small syntax error in your JavaScript code, but it's easy to correct.
What Went Wrong in Your Original Code
Looking at your JS snippet:
$('#url').on('change keyup paste',function(){ $('#msg')style.visibility('visible');});
Two issues are breaking it:
- You’re missing the dot operator between the jQuery object
$('#msg')andstyle– but even if you added that, using native DOM properties directly with a jQuery object isn't the cleanest approach here. - The syntax for setting the visibility property is incorrect: native DOM uses assignment (
= 'visible'), not a function call, and jQuery has its own dedicated method for modifying CSS.
Corrected jQuery Code
Here's the working version using jQuery's .css() method, which is the proper way to adjust CSS properties with jQuery:
$('#url').on('change keyup paste', function() { $('#msg').css('visibility', 'visible'); });
How This Works
$('#url').on('change keyup paste', ...): This part is actually correct! It properly listens for the three events you specified on the#urlelement.$('#msg').css('visibility', 'visible'): The.css()method takes two arguments: the name of the CSS property you want to change, and its new value. This will update thevisibilityproperty of your#msgelement tovisible, making it show up as intended.
Alternative: Plain JavaScript (No jQuery)
If you prefer to skip jQuery and use native JS instead, here's an equivalent version:
// Get references to the elements const urlInput = document.getElementById('url'); const msgElement = document.getElementById('msg'); // Create a reusable function to show the message function showMessage() { msgElement.style.visibility = 'visible'; } // Attach event listeners urlInput.addEventListener('change', showMessage); urlInput.addEventListener('keyup', showMessage); urlInput.addEventListener('paste', showMessage);
Quick Troubleshooting Tip
If you're using jQuery, double-check that you've included the library before your custom script. If jQuery isn't loaded, the $ function will be undefined, and your code won't run:
<!-- Include jQuery first --> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <!-- Then your custom script --> <script> // Your corrected code here </script>
内容的提问来源于stack exchange,提问作者 elison




