简体   繁体   中英

How to execute a function on an element that has been selected by the value of a data-attribute?

Sorry for the long winded question. My scenario is this.

I have 10 HTML consecutive elements, each listed as so: (I have left the divs empty for the sake of clarity as they're not relevant)

<div class="item" data-id="1" style="left: 0px; top: 0px; transform: translateX(0px) 
translateY(0px)">
  <div class="item-content">
    <div class="card-add"> </div>
 </div>
</div>

All of the elements are identical apart from the 'data-id' attribute. Within each element the data-id ranges from 1-10. What I am aiming to do is select the 'item' by its data-id value, and then execute a function on the 'card-add' div relative to the item selected. The value to be selected will be randomly generated from specific numbers numbers.

My code so far:

// select the value

     myNumbers = [1, 2, 6, 9, 11];
     var item = myNumbers[Math.floor(Math.random() * myNumbers.length)];


 // use this to select the current item

     var itemTemp = ($("[data-id=" + item + "]"));


// attempting to execute a function on this.

      $(itemTemp).find(".card-add").each(function() { 
        *do stuff here*
      }

Obviously, this doesn't seem to be working. I think it has something to do with binding the 'find' and 'each' function.

Does anyone have solutions around this?

Change the speech marks to quotations:

$(itemTemp).find('.card-add').each(function() { do something }

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