简体   繁体   中英

Getting text from an element with the same class name using jQuery

I've got a little drag and drop app which i've built. It's working OK, but there is a slight issue where I drag on the item to the droppable location.

It should get the text from the HTML (which is does) and update another div to show the user what they've dragged in.

Unfortunately, it always returns the same name, no matter which list item you drag. This is the first in the list, so the first instance of that class.

Anyway we can get the correct label for the item dragged?

Here is my jQuery

$(function() {
    $( ".drag_me" ).draggable({ revert: "invalid" });
    $( ".choc2_bowl" ).droppable({
      drop: function( event, ui ) {
        $( this )

            var htmlString = $('.choc_label').html();
            $('.choc2_flavour').text( htmlString );

            ui.draggable.fadeOut(500);
      }
    });
  });

An here is the list in my HTML (this is shortened for this demo, but the list is dynamic from a DB.

<div class="choc2_select">
<ul>
<li class="drag_me"><div ><img src="RASPBERRY.png" /></div><div class="choc_label">Raspberries</div></li>
<li class="drag_me"><div ><img src="CHAMPAGNE.png" /></div><div class="choc_label">Strawberries</div></li>
<li class="drag_me"><div ><img src="DRIED-BLUEBERRIES.png" /></div><div class="choc_label">Blueberries</div></li>
<li class="drag_me"><div ><img src="CHAMPAGNE.png" /></div><div class="choc_label">Cranberries</div></li>
</ul>
</div>

Any help would be greatly appreciated!

Simon

You need to target the choc_label inside the dragged element so use

$(".choc2_bowl").droppable({
    drop: function (event, ui) {
        var htmlString = ui.draggable.find('.choc_label').html();
        $('.choc2_flavour').text(htmlString);
        ui.draggable.fadeOut(500);
    }
});

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