简体   繁体   English

JQuery 比较列表项的 Class

[英]JQuery Compare Class of List Items

Using JQuery I want to check that each list item has the css class Complete .使用 JQuery 我想检查每个列表项是否具有 css class Complete If so, i want to display a button, if not I want to keep the button hidden.如果是这样,我想显示一个按钮,如果不是,我想隐藏按钮。

The classes are currently inserted dynamically using PHP when the page loads.当前页面加载时,这些类是使用 PHP 动态插入的。

My code so far is;到目前为止,我的代码是;

<button id="steps-complete" hidden>Download Now</button>

<ul class="wb-steps">
    <li class="<?php echo $class ?>">Step 1</li>
    <li class="<?php echo $class ?>">Step 2</li>
    <li class="<?php echo $class ?>">Step 3</li>
</ul>

<script>
jQuery( document ).ready(function() {
    var steps = [];
    jQuery( ".wb-steps li" ).each(function( index ) {
        // successfully displays complete for each list item
        console.log( index + ": " + jQuery( this ).attr('class') );
        // if all stepa have 'complete' show button
        $("#steps-complete").show();
    });
});
</script>

You have the $class variable, and its value is set as the class of all list items.您有$class变量,其值设置为所有列表项的 class。

Since you are using PHP to render the page, you can use the same variable to test if the button should be shown or not.由于您使用 PHP 来呈现页面,因此您可以使用相同的变量来测试是否应该显示按钮。 So you wouldn't need jQuery in this case, you can just remove that part.所以在这种情况下你不需要 jQuery ,你可以删除那部分。

Here's what it would look like:这是它的样子:

<?php
if (strpos($class, 'Completed') !== false) {
?>
<button id="steps-complete" hidden>Download Now</button>
<?php
}
?>

This works in your case because you set the same class to all items.这适用于您的情况,因为您为所有项目设置了相同的 class。

Hope this helps.希望这可以帮助。

You can simply count the elements to see if all of them have the complete class:您可以简单地计算元素,看看它们是否都有complete的 class:

jQuery(document).ready(function() {
    var $steps = $(".wb-steps li");
    var show = $steps.length === $steps.filter('.complete').length;

    $("#steps-complete")
        .toggle(show)
        .get(0)
        .toggleAttribute('hidden', show);
});

i've made a function to check of the children of the wb-steps have a class named john, if not then we show the steps complete我制作了一个 function 来检查wb-steps是否有一个名为 john 的 class,如果没有,那么我们显示步骤完成

 jQuery( document ).ready(function() { if($(".wb-steps").children().not('.john').length = 0){ console.log("there was a div found with a class named john"); }else{ $("#steps-complete").show(); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="steps-complete" hidden>Download Now</button> <ul class="wb-steps"> <li class="<?php echo $class?>">Step 1</li> <li class="<?php echo $class?>">Step 2</li> <li class="<?php echo $class?>">Step 3</li> </ul>

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

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