简体   繁体   中英

How can I choose one element out of multiple to clone into a separate section? (Have it working hard coded, looking to save time and resources)

I hope this will make sense since I can't use a JS fiddle because it doesn't support C# Models (at least not that I can tell). Basically I am trying to clone a product in one div to another div when that product is selected.

Here is the html and c#:

<%
    var i = 0; 
    foreach (var product in Model.Products)
    {
%>

        <li class="l-row__item" id="product<%=i %>" >

        <div> 
            Contains styling like photos, product titles, etc. I don't think you'll need this information, its super long.
        </div>

        </li>
<%
        i++;
    }
%>

My script:

$("#product1").on("click", function () {
    var offercart = $("#product1").clone();
    $("#offer-grid").append(offercart);
});

So as you can see, I turned all the li's so they have IDs such as product 1. Now if I click product 1 (or actually its two but you all know that) it will clone product one to the other div. However, there are over over 50 products. So I know instead of copying and pasting this code over and over there has to be an easier way.

I'm a beginner so I'm sorry if the answer is obvious. I was proud of myself for getting this far without help! (Backend friend did the C# stuff, I just do the jQuery and JS!) If someone could tell me where to begin, a hint or give me an example in JS Fiddle as a guide I'd be so grateful. I'm really enjoying learning JavaScript and hope to be able to contribute to this awesome community one day!

Also if this has already been answered by someone else please link me and I'll delete this asap. I tried all kinds of search terms but didn't find one that matched but I could have been wording it wrong.

Try -

$(".l-row__item").on("click", function () {
var offercart = $(this).clone();

Will do apply to every row item.

You should use Class Selector (".class") , In example I have added product css class

IMHO, you can store some information like product id in data-* attributes.

<%foreach (var product in Model.Products){%>

    <li class="l-row__item product" data-product-id="<%= product.id %>">
        <div> Contains styling like photos, product titles, etc.
        I don't think you'll need this information, its super long.</div>
    </li>

<%} %>

script:

$(".product").on("click", function () {
    var offercart = $(this).clone();
    var productid = $(this).data('product-id');
    $("#offer-grid").append(offercart);
});

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