简体   繁体   中英

How to get the value of an attr jquery

I've dynamically created multiples divs and I randomly assigned an attribute id ,called mine-data with a value of 10, to some of them, now I'm creating a function that looks for divs with attribute 'mine-data' and returns true. but it doesn't work. I've looked at similar questions and none of the answers worked. Any idea how to make it work?

function isattr() {
    var attrb=$('.grid').attr('mine-data');    
    if(attrb==10) { 
       return true;
    }
}

$('.grid') will return object contains all of element with class .grid . If you want to create a checking function , you need to pass each of it. please review this one

 function isattr(elm) { var attrb = $(elm).attr('mine-data'); //compare with string 10 if (attrb === '10') { return true; } return false; } //get the array var arrs = $('.grid').toArray(); //check for each element arrs.forEach(function(elm) { // here we check each element and addEventListener $(elm).on('click', function(e) { console.log(isattr(this)); }); }) 
 <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script> <div class="grid" mine-data=10>ok</div> <div class="grid" mine-data=10>ok</div> <div class="grid" mine-data=9>not</div> <div class="grid">not</div> <div class="grid" mine-data=10>ok</div> 

You need to use $.each() . Then supply a function inside which $(this) will be the concrete element.

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