简体   繁体   中英

jQuery: Prevent child from inheriting the parent's attributes?

With jQuery: How do I prevent the children ( <span> ) from inheriting the parents' ( <p> ) attributes? I've been working on and researching this for 2+ hours; nothing has worked.

Problem section:

$("p").not("span").css("cursor", "pointer");

<p>...<span>...</span></p>

Full code:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<style>body {font-family:Arial,san-serif;font-size:25pt;}</style>
<body>
<p>Always shown | <span>Show/Hide</span></p>
<p>Always shown | <span>Show/Hide</span></p>
</body>

<script>
//Change pointer to a hand:
$("p").not("span").css("cursor", "pointer");
//Show & Hide by clicking on "Always shown":
function handler(event) {
  var target = $(event.target);
  if (target.is("p")) {
    target.children().toggle();
  }
}
$("body").click(handler).find("span").hide();
</script>

Why don't you use css?

p{ cursor: pointer; }
p span{ cursor: default; }

The expression $("p").not("span") literally means "select p elements that are not spans " . Obviously it is always true.

You want to check if p does not contain span children:

$("p:not(:has(span))").css("cursor", "pointer");

However, for this task you should probably go with CSS solution, rather then javascript.

You could try this: fiddle

p:hover {
    cursor: pointer;
}
span:hover {
    cursor: default;
}

You can do this approach also if you want to be done on Jquery :

$("p").css("cursor", "pointer");
$("p span").css("cursor", "default");

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