简体   繁体   中英

HTML: jQuery: DOM manipulation

I'm lazy. There! That's out of the way.

I have a list of items of indeterminate length which I would like to render in HTML. I want to show a part of each item and then have a "show more" link in each item which will show more of the item. Since the "show more" link implements the same functionality, I bound the same click handler function to the "show more link" which then shows the HTML span which contains the hidden text. My code looks like this:

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script> 
</head>
<body>
<p>List of stuff</p>
<ul>
    <li> One <a href="#" class="showmore_link">show more</a>  <span class="showmore" style="display:none"> More about One </span></li>
    <li> Tow <a href="#" class="showmore_link">show more</a>  <span class="showmore" style="display:none"> More about Two </span></li>
    <li> Three <a href="#" class="showmore_link">show more</a>  <span class="showmore" style="display:none"> More about Three </span></li>
</ul>
<script type="text/javascript">

     $(document).ready(function() {
        $(".showmore_link").click(show_more_toggle);
     });

     show_more_toggle=function(){
        $(".showmore").slideToggle();
     }

</script>
</body>
</html>

When I click the "show more" link, it shows all three spans of class "showmore". How can I adjust the "show_more_toggle" click handler so that it only opens up the span in the same list item?

CONSTRAINT: I cannot use "id" attributes on the spans or the list elements for other reasons.

$('a.showmore_link').click(function() {
    $(this).next().show();
});

Try -

 show_more_toggle=function(){
    $(this).siblings(".showmore").slideToggle();
 }

Demo - http://jsfiddle.net/ipr101/9GB9u/

another solution:

$(document).ready(function() {
    $(".showmore_link").click(function() {
        $(this).parent().children(".showmore").slideToggle();
    });
});

http://jsfiddle.net/A7fM5/

使用next() -它将使您获得span元素。

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