开发者

jQuery - show the content of a div by a link without id/class references

I have this code :

function showContent() {
    ...
}

<div id="example">
    content
    <a href="#" onClick="showContent();return false">Link</a>
</div>

I'd like, when I click on the Link, show the content of the div, without using id or class a开发者_JAVA技巧s reference, but (maybe) the simple this.

How can I do it?


Well, there's not a whole lot of context, but this is one way:

<div id="example">
 <p style="display: none;">content</p>
 <a href="#" onClick="showContent(this);return false">Show content above</a>
</div>

function showContent(el) {
    $(el).parent().children(':first-child').show();
}

http://jsfiddle.net/LeVFb/

Or, if you wanted to show all within (and I don't think the :not really matters* in this case):

function showContent(el) {
    $(el).parent().children(':not(a)').show();
}

*In fact, I would go ahead and say leave it off unless you have a specific reason not to:

function showContent(el) {
    $(el).parent().children().show();
}

It would depend on the content you're trying to display and whether any A tags are display: hidden and need to be shown.

http://jsfiddle.net/LeVFb/2/

This could go a number of ways.


You're going to have to wrap the "content" in a <div> (or some other block element):

<div id="example">
    <div style="display: none;">content</div>
    <a href="javascript:void(0)" onClick="showContent(this)">Link</a>
</div>

And don't use href="#" for these sorts of links, href="javascript:void(0)" is a better choice that causes fewer problems; the void(0) approach also means that you don't need return false in your click handler to keep the browser from trying to interpret an empty fragment.

Back to our regularly scheduled program. Then, your showContent becomes quite simple:

function showContent(e) {
    $(e).prev('div').show();
}

A better way is to use jQuery to bind the click handler:

<div id="example">
    <div style="display: none;">content</div>
    <a href="javascript:void(0)">Link</a>
</div>

And then:

$('#example a').click(function() {
    $(this).prev('div').show();
});


If the link is within the div, you could do this...

<a href="#" onClick="showContent(this);return false">Link</a>

then in your function...

function showContent(link){
     alert($(link).parent().html());
}

However, this assumes that the div is visible already so you wouldn't need to "show" it.


Try using the jquery parent selector

$(this).parent('div').show()

However, how is the link visible, if the containing div is not?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜