如何在不使用css选择器的情况下使用jquery切换<li>元素的子元素?</li>

时间:2015-03-05 18:46:14

标签: jquery html

我有这个列表,当我悬停其中一个锚标签时,我希望其父li的p元素在隐藏和显示之间切换。不幸的是在我的代码到目前为止,当我悬停锚标签时,它切换列表中每个li元素的p元素。如何只选择父李的p?这是我的代码。对不起,我是jquery的新手。

<body>
<div id="container">
<ul>
  <li>
    <a href="#"><h3>CIST 2612 Computer Forensics</h3></a>
    <p>(Prerequisite: CIST 1122, CIST 1601). This course examines the use of computers in the commission of crimes, collection, analysis and production of digital evidence. Students will use computer resources to explore basic computer forensic investigation techniques.</p>
  </li>
  <li>
   <a href="#"><h3>CIST Web Technologies</h3></a>
    <p>(Prerequisite: CIST 1001) In Web Technologies, students will investigate one or more software packages that help automate Web content creation. Students will explore and utilize various features of software packages such as CSS, multimedia incorporation, scripting technologies, form creation, search functionality, advanced image techniques and database connectivity. </p>
  </li>
  <li>
    <a href="#"><h3>CIST 2531 Web Graphics II </h3></a>
    <p>(Prerequisite: CIST 1530) Students will further explore how to use and industry standard or open source graphics software program to create Web ready images and Web pages. Topics include advanced image correction techniques and adjustments, typography and interpolation as well as conditional scripting statements and arrays. </p>
  </li>
</ul>
</div>
</body>





$(function(){

$("li").children('p').hide();

});


$(document).ready(function(){
    $("a").hover(function(){
     $("li").children("p").toggle(200);
    });
});

http://codepen.io/anon/pen/GgBBMr这是我工作的代码。 谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

例如demo1 demo2

$("a").hover(function(){
     $(this).closest("li").find("p").toggle(200);
});

$("a").hover(function(){
     $(this).siblings("p").toggle(200);
});

答案 1 :(得分:0)

以下是使用父级范围的分步方法:

$("a").hover(function () {
    // First, you have 'this' which is the '<a>' that you are hovering.
    var $this = $(this);
    // Second, find the parent 'li'
    var $parentLi = $this.parent('li');
    // Now we find all the '<p>' tags inside the parent '<li>' scope
    var $allPTags = $('p', $parentLi);
    //now toggle them
    $allPTags.toggle(200);
});

你可以将所有内容串在一起,但我通常更喜欢创建变量,因为在现实生活中,它通常不像将简单函数串联起来那么容易。

$("a").hover(function () {
    var $parentLi =  $(this).parent('li');
    // still using scope
    $('p', $parentLi).toggle(200);
});

$("a").hover(function () {
    $(this)
        .parent('li') // find parent <li> can also use .closest('li') but closest traverses the DOM all the way up until if finds an 'li' which might not be what you want. .parent() ensures your are selecting the parent.
        .find('p') // find <p> inside parent <li>
        .toggle(200); // toggle
});