简体   繁体   中英

jQuery Closest/Parent not working

What's going wrong in this code? Nothing happens on click

HTML

  <p>Click me</p>
    <h1 class="myClass">...........</h1>

  <p>Click me</p>
    <h1 class="myClass">-----------</h1>

CSS

hilight {
    background-color: yellow;
  }

jQuery

$( document ).on( "click", "p", function( ) {
  $( this ).closest( ".myClass" ).toggleClass( "hilight" );
});

Live example https://jsfiddle.net/djuccj7b/

You can use Next Adjacent Selector ("prev + next") with context set to this : p element to select h1 element that is next element sibling of clicked p element

$( document ).on( "click", "p", function( ) {
  $( "+ .myClass", this ).toggleClass( "hilight" );
});

Also, your css is missing . before hilight

.hilight {
    background-color: yellow;
}

jsfiddle https://jsfiddle.net/djuccj7b/2/

  1. Change closest() to next()
  2. Put a period in front of your class name in the css....

    .hilight { background-color: yellow; }

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