简体   繁体   English

如何获取attr jQuery的值

[英]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. 我已经动态创建了多个div,并向其中一些对象随机分配了一个名为id的属性ID(称为mine-data),其值为10,现在,我正在创建一个函数来查找具有“ mine-data”属性的div并返回真正。 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 . $('.grid')将返回包含类.grid所有元素的对象。 If you want to create a checking function , you need to pass each of it. 如果要创建checking function ,则需要传递每个checking function 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() . 您需要使用$.each() Then supply a function inside which $(this) will be the concrete element. 然后提供一个函数,其中$(this)将是具体元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM