开发者

Thinking of two elements as "the same"

I have two jQuery elements, $link = $('<a>') and $input = $('<input/>').

Although they are two different types of elements, they are in my code (and in my mind!) very linked:

1) Conceptually, they are different representations of one object.

2) They share the same attributes.

3) When one is displayed on the screen, the other is hidden.

Until now, I have used .data() to perform a link between the two:

$link.data('$input', $input);
$input.data('$link', $link);

As my code became more and more complex, this solution has proved confusing and 开发者_如何学Gomessy.

Is there a different approach I may want to consider? For example, is there a way to keep the attributes of the two elements continually synced? Is there a way to make one "meta-object" out of the two? etc.


Yes, use .add()

$link = $('<a>');
$input = $('<input />');
$both = $link.add($input);
$both.doStuff(); //Will apply to both


Using IDs

Each of those elements should have a proper id attribute.

You can use the IDs to lookup other elements.

Example

HTML:

<a href="#" id="obj-1-a">Link</a>
<input id="obj-1-input" />

Javascript:

$('a').click(function() {
    $('input#' + this.id.replace(/a/, 'input')).show();
    $(this).hide();
});

$('input').click(function() {
    $('a#' + this.id.replace(/input/, 'a')).show();
    $(this).hide();
});

Live demo.


Using structure

Alternatively, you may use simple structuring to group your elements.

This has the advantage that you do not need to provide an id attribute for each of your DOM elements, but it may restrict you in terms of where you can place your elements within the DOM tree.

Example

In the example below, I use the fact that the a and input are siblings (both children of the same div) to consider them "linked".

There are many variations of this concept; below is shown just one of them.

HTML:

<div>
    <a href="#">Link 1</a>
    <input value="Input 1" />
</div>

Javascript:

$('a').click(function() {
    $(this).hide().siblings('input').show();
});

$('input').click(function() {
    $(this).hide().siblings('a').show();
});

Live demo.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜