简体   繁体   中英

How to set HTML attribute in conditional rule with jQuery?

I'm still confused about how to set other class attribute in an element according to other element attribute in dynamic number.

Here are my HTML & PHP:

<?php for($i=1;$i<=$total;$i++){ ?>
<a href="#no<?php echo $i;?>" id="shorcut<?php echo $i;?>" class"not-yet"><?php echo $i;?></a>
<?php } ?>

<div id="no<?php echo $no?>" class="<?php if(!empty($h->answer)){ echo 'answered';} else{ echo 'not-yet';} ?>">

And here are my javascript:

$(document).ready(function(){

 var i;
 var tot = <?php echo $jumlah;?>
 for (i=1; i< tot; i++){
    if($('#no'+i).hasClass('answered'){
       $('#shortcut'+i).attr('class', 'answered');
    }
 }
});

For example when <div id="1"> has a class attribute "answered" then set <a href="no1" id="shortcut1" class="answered"> (change class from "not-yet" to "answered" )

Help me and thanks for your attention

Use $(..).addClass('classname') and $(..).removeClass('classname') to change class attributes.

$(function(){
    var tot = <?php echo $jumlah;?>;
    var i;
    for (i=1; i<tot; i++) {
       if ($('#no'+i).hasClass('answered')) {
           $('#shortcut'+i).addClass('answered');
       }
    }
});

Here's a quick and dirty solution to your javascript

http://jsfiddle.net/w9uvR/

Basically you just want to do this for each div:

   $(document).ready(function() {
       $("[id^='no']").each(function() {
            if(this.className == "answered") {
               var myId = this.id.replace("no","");
                $("#shortcut" + myId).attr("class", "answered");
             }
        })
    });

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