Can't update data-attribute value

后端 未结 9 1559
北海茫月
北海茫月 2020-11-27 17:11

Although there are some examples about this on the web, it does not seem to work correctly. I can\'t figure out the problem.

I have this simple html

         


        
9条回答
  •  长情又很酷
    2020-11-27 17:23

    I had the same problem of the html data tag not updating when i was using jquery But changing the code that does the actual work from jquery to javascript worked.

    Try using this when the button is clicked: (Note that the main code is Javascripts setAttribute() function.)

    function increment(q) {
    
        //increment current num by adding with 1
        q = q+1;
    
        //change data attribute using JS setAttribute function
        div.setAttribute('data-num',q);
    
        //refresh data-num value (get data-num value again using JS getAttribute function)
        num = parseInt(div.getAttribute('data-num'));
    
        //show values
        console.log("(After Increment) Current Num: "+num);
    
    }
    
    //get variables, set as global vars
    var div = document.getElementById('foo');
    var num = parseInt(div.getAttribute('data-num'));
    
    //increment values using click
    $("#changeData").on('click',function(){
    
        //pass current data-num as parameter
        increment(num);
    
    });
    

提交回复
热议问题