简体   繁体   中英

How to associate two DOM elements?

I have this simple HTML structure:

<ul>
    <li> One <p> Foo is a fool. </p> </li>
    <li> Two <p> Bar is not Barbie. </p> </li>
    <li> Three <p> Baz likes bazookas. </p> </li>
</ul>

<div id="pane"></div> 

As you can see, there is a UL list. Each LI item contains a paragraph that is at all times hidden.

What I want to do is this:
Whenever the user clicks a LI element, the corresponding P element should be transfered to the #pane DIV. And then, when the user clicks the same LI element again, the P element should be transfered back to its original location.

Live demo: http://jsfiddle.net/u5y6u/1/

This is the jQuery code that I'm using currently:

var p;

$('li').toggle(function() {
    p = $(this).find('p').appendTo('#pane');
}, function() {
    p.appendTo(this);
});

The local variable p is used to store the reference to the paragraph when it is inside the #pane DIV. This obviously works only for one LI element, because if the user clicks on one LI element and then immediately after that on another LI element, the p variable is overwritten with the new paragraph reference.

This is what I would like to do:
Whenever a P element is transfered to the #pane DIV, I want to somehow associate that P element with the LI element that originally contained it, so that when the LI is clicked again, I know which P element I have to transfer back.

How would I do this?

You could

  1. use naming convention for ids: li has the same id as p plus li- prefix

  2. store p id in li's data- attribute

  3. use the same css class for each pair of li / p

You could use the data() (docs) method and/or the jQuery.data() (docs) method to give each <li> element a reference to its <p> element.

http://jsfiddle.net/u5y6u/3/

$('li').each(function() {
    var $th = $(this);
    $th.data('relatedP', $th.find('p'));
})
.toggle(function() {
    $.data(this,'relatedP').appendTo('#pane');
}, function() {
    $.data(this,'relatedP').appendTo(this);
});

Well one way you could do it is with an each statement to give each p it's own scope. See fiddle

$('li').each(function(){
    var p = $(this).find('p');

    $(this).toggle(
        function() { p.appendTo('#pane'); },
        function() { p.appendTo(this); }
    );
});

If you can put your dynamic content in the 'pane' div and toggle the visibility, the logic becomes a bit simpler. Here is an example:

http://jsfiddle.net/rcravens/u5y6u/4/

Bob

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