繁体   English   中英

如何从元素中获取价值并在javascript选项中使用它

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

我有Adobe Muse生成的这个简单的html(我无法直接更改):

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

我从CountUp脚本中获得了以下选项:

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

问题是:

我需要找到所有带有title="counter"元素,为每个<p>设置ID,然后从<p>1290</p>获取值,将其放入脚本选项并分别运行每个计数器。

我尝试这样做:

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();
});

我哪里错了?

我相信您正在寻找的可能是这样的:

/* 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);

编辑:

我不明白,为什么你使用

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

这会在数组中的键中添加“计数器”,您也可以使用

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

然后在$.each “循环”中传递jQuery对象,而不是您提供的展示所需的id字符串。 如果您(出于任何原因)继续在字符串数组中添加字符串“ counter”,则必须像这样转换循环:

$.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();
});

因此,这也许也可行,并且可能会更好地理解

$.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();
});

暂无
暂无

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

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