简体   繁体   中英

how to clone variable html element in JQuery

I have a set of divs which are elements of database and I want to set an event for each of them so that if I click on one of them it will be cloned. I tried something but it didn't work, here is the code on my page :

<% @ideas.each do |idea| %>    
<div id="idea_<%=idea.id%>" class="idea">
    <%= idea.title %>
</div>
<% end %> 

And here is the CoffeeScript code :

ideas = document.getElementByClassName("idea") 
for iter in [0..ideas.length - 1]
  do ->
    ideas[iter].(get_id).click -> ideas[iter].(get_id).clone().appendTo('.container');

Any ideas ?

Here is a slightly modified version that should do what you are looking for. One thing to always keep in mind in Javascript/Coffeescript is the scope that your code will be running in. In this case, it is very important to use the do keyword so that the iter variable is properly captured. Without it, when you clicked any idea, it would always clone the last idea, because by the time the click handler actually executes, iter will have reached the end of the loop.

ideas = document.getElementByClassName("idea") 
for iter in [0...ideas.length]
  do (iter) ->
    ideas[iter].click -> ideas[iter].clone().appendTo('.container');

Here is a modified version that is a bit cleaner as well. jQuery can handle all of that iteraction for you.

$('.idea').click ->
    $(@).clone().appendTo('.container')

What are you trying to do with the 'get_id' part? I'm just kind of ignoring it, so let me know if I misunderstood.

Edit:

To only clone once, the easiest way is to use jQuery's 'one' method instead of 'bind'.

$('.idea').one 'click', ->
    $(@).clone().appendTo('.container')

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