Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>$('#allContents').on('click', 'div[id^=A]', function() { $('div#B' + this.id.replace('A','')).slideToggle(); }); </code></pre> <h3>A little explain</h3> <ul> <li><code>div[id^=A]</code> point out those <code>div</code> whose <code>id</code> start with <code>A</code>.</li> <li><code>this.id</code> retrieve the <code>id</code> of clicked element.</li> <li><code>this.id.replace('A','')</code> replace <code>A</code> form the <code>id</code> and get the numeric index which equal to index of <code>B</code>.</li> <li><code>$('div#B' + this.id.replace('A',''))</code> point to element <code>id=B1</code>, <code>id=B2</code> and so on.</li> </ul> <p><strong>Full code</strong></p> <pre><code>// you can bind event handler outside ot loop $('#allContents').on('click', 'div[id^=A]', function() { $('div#B' + this.id.replace('A','')).slideToggle(); }); $.each(items, function(index, item) { $("#allContents").append('&lt;div id="A' + i + '"&gt;' + item.name + '&lt;/div&gt;'); $("#allContents").append('&lt;div id="B' + i + '"&gt;' + item.Details + '&lt;/div&gt;'); i++; }); </code></pre> <p><strong><a href="http://jsfiddle.net/vQzSv/9/" rel="nofollow">Working Sample</a></strong></p> <hr> <h3>Note</h3> <p>As you're creating <code>div</code> from <code>A(1..N)</code> and <code>B(1..N)</code> dynamically so you need delegate event handler (aka live event).</p> <p>Syntax of jQuery <strong><a href="http://api.jquery.com/on" rel="nofollow"><code>.on()</code></a></strong> for delegate event is like following:</p> <pre><code>$(container).on(eventName, target, handlerFunction) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload