简体   繁体   English

jQuery:防止孩子继承父级的属性?

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

With jQuery: How do I prevent the children ( <span> ) from inheriting the parents' ( <p> ) attributes? 使用jQuery:如何防止子级( <span> )继承父级( <p> )属性? I've been working on and researching this for 2+ hours; 我一直在研究2个小时以上; 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? 为什么不使用CSS?

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

The expression $("p").not("span") literally means "select p elements that are not spans " . 表达$("p").not("span")字面意思是“选择p不在元件spans ”。 Obviously it is always true. 显然,这始终是正确的。

You want to check if p does not contain span children: 您要检查p是否不包含span子代:

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

However, for this task you should probably go with CSS solution, rather then javascript. 但是,对于此任务,您可能应该使用CSS解决方案,而不是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 : 如果您想在Jquery上完成操作,也可以使用这种方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM