简体   繁体   中英

How to get value from elements and use it inside of javascript options

I have this simple html generated by Adobe Muse (I can't change it directly):

<div id="randomID" title="counter"><p>1290</p></div>

And I have this options from the CountUp script:

var counter = new countUp( 'counterID', 0, *Some Value*, 0, 2 ); 
counter.start(); // run counter

The question is:

I need to find ALL elements with title="counter" , set ID's for each <p> , then get value from <p>1290</p> , put it into the script options and run each counters separately.

I tries to do this:

var counters={};
$("[title='counter']").each(function(){
counters['counter' + this.id]=$(this).children('p').html();   });

$.each( counters, function( id, value ) {
var id = new countUp( $('#' + id), 0, value, 0, 2 );
id.start();
});

Where I'm wrong?

I believe what you are looking for might be this:

/* jquery */
var result={};
$("div[title=counter]").each(function(){
    result[this.id]=$(this).find("p").html();    
});
console.log(result);

/* pure js */
var result2={};
var allP=document.getElementsByTagName("p");
for(var i=0, len=allP.length; i<len; i++){
    var parent=allP[i].parentNode;
    if(parent.nodeName=="DIV" && parent.title=="counter")
        result2[parent.id]=allP[i].innerHTML;
}
console.log(result2);

EDIT:

I do not see, why you use

counters['counter' + this.id]=(...) // why adding 'counter'?

which adds 'counter' to your key inside array, you could have as well just used

counters[this.id]=(...)

then in your $.each 'loop' you pass jQuery object instead of id string as required by showcase you provided. If you keep (for any reason) adding string 'counter' to key in your array, you will have to transform your loop like this:

$.each( counters, function( id, value ) {
    // you should name variables differently, maybe key and counter, or key and id, just avoid naming two different variales same
    var id = new countUp( id.substr(7), 0, value, 0, 2 );
    id.start();
});

So perhaps this might work as well and might be understood better

$.each( counters, function( key, value ) {
      var objCounter = new countUp(key.substr(7), 0, value, 0, 2);
      objCounter.start();
      // which could be replaced by (new countUp(key.substr(7), 0, value, 0, 2)).start();
});

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