简体   繁体   中英

How to add jQuery to html

I tried this:

<script src="js/jQuery.js"type="text/JavaScript"></script>

Then I tried to call a click function on my button:

<script>
  $(document).ready(function (){
    function jfn1(){
      $("jbtn").fadetoggle()
    }
  })
</script>

I'm not sure what you're trying to achieve but with the code below, clicking on the button with class 'jbtn' will make it fade out.

 $(document).ready(function (){ $('.jbtn').click(function() { $( this ).fadeToggle(); }); })
 <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <button class="jbtn">Hey!</button>

Welcome to StackOverflow, Chisom.

All you did was define that function, you didn't actually call it. Also it needs to be " fadeToggle ", not " fadetoggle ".

  /**
   * Define function to fade button in/out
   */
  function jfn1 () {
    $("jbtn").fadeToggle() // "fadeToggle", not "fadetoggle"
  }

  /**
   * On document ready (DOM loaded)
   */
  $(document).ready(function (){
    // Call function on document ready
    jfn1()
  })

This will call "fadeToggle" when the DOM tree is loaded. If you want to call it when clicked, it needs to look like this:

  /**
   * On document ready (DOM loaded)
   */
  $(document).ready(function (){
    // On button clicked
    $("jbtn").click(function () {
      // "this" is the function context
      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
      $(this).fadeToggle()  
    });
  })

Also $("jbtn") will only find HTML elements that look like this: <jtbn>...</jtbn> . If you want to refer to a class ( <HTML_ELEMENT class="jtbn"></HTML_ELEMENT>... ), you should prefix it with a dot like this: $(".jbtn") .

Good luck!

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