简体   繁体   English

如何比较父母和孩子的数据属性?

[英]How to compare data attributes of parent and child?

I'm trying to compare the data attributes of a child div to its parent div and if they do not match then hide the child element. 我正在尝试将子div的数据属性与其父div进行比较,如果它们不匹配,则隐藏子元素。 I want to be able to compare for each instance of the parent child relationship. 我希望能够对父子关系的每个实例进行比较。 .test is the parent and .event is the child. .test是父级,.event是子级。 Here is what I have. 这就是我所拥有的。

    if ($(".event").data("campaign-id") != $(".event").parent().data("campaign-id")) {
        $(".event").hide();
    }

data as getter returns specified datum of the first selected element in the set. 作为getter的data返回集合中第一个选定元素的指定基准。 Your script hides the all .event elements when the first .event element's campaign-id datum matches with it's parent campaign-id datum. 您的脚本隐藏所有.event元素时,第一.event元素的campaign-id数据匹配与它的父campaign-id数据。 You could use the .filter() method: 您可以使用.filter()方法:

$(".event").filter(function() {
   return $(this).data("campaign-id") !== $(this.parentNode).data("campaign-id");
}).hide();

If you are getting data-campaign-id attributes and not the data stored by jQuery, another option is: 如果要获取data-campaign-id属性而不是jQuery存储的数据,则另一个选择是:

[].forEach.call(document.querySelectorAll('.event'), function(el) {
    var c = el.getAttribute('data-campaign-id'),
        p = el.parentNode.getAttribute('data-campaign-id');
    if ( c !== p ) {
        el.style.display = 'none';
    }
});

You can use .each() for this task: 您可以使用.each()完成此任务:

 $(".event").each(function(){
     if($(this).data("campaign-id") != $(this).parent().data("campaign-id"))    
     {
          $(this).hide();
     }
 });

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

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