我是编程和堆栈溢出的新手,所以请原谅我,如果我没有妥善格式化我的问题:)
我试图循环遍历包含三个跨度的数组,并记录“数据强度”属性值。 我可以用$el[i]获得单个跨度,并且还可以使用$el.attr('data-strength')获取属性值。 当我将两者结合后, $el[i].attr('data-strength')会返回一个错误。 我认为这是一个语法错误,但我喜欢一些指导。
我还包括下面的笔连接。 谢谢!!!
<div id="container"> <button id="trigger">Click Me</button> <div id="strength"> <span data-strength="60"></span> <span data-strength="50"></span> <span data-strength="40"></span> </div> </div> var $trigger = $("#trigger"), $el = $("#strength span"), $counter = $el.length; $trigger.click(function(){ for(var i = 0; i < $counter; i++){ var $result = $el[i].attr('data-strength'); console.log($result); } });https://codepen.io/joeylane/pen/dmGpdq
I am new to programming and stack overflow, so please forgive me if I am not formatting my question properly :)
I'm trying to loop through an array containing three spans, and log the 'data-strength' attribute value. I am able to get the individual spans with $el[i], and am also able to get the attribute value with $el.attr('data-strength'). When I combine the two however $el[i].attr('data-strength'), an error is returned. I assume this is a syntax error, but I'd love some guidance.
I've also included the pen link below. Thanks!!!
<div id="container"> <button id="trigger">Click Me</button> <div id="strength"> <span data-strength="60"></span> <span data-strength="50"></span> <span data-strength="40"></span> </div> </div> var $trigger = $("#trigger"), $el = $("#strength span"), $counter = $el.length; $trigger.click(function(){ for(var i = 0; i < $counter; i++){ var $result = $el[i].attr('data-strength'); console.log($result); } });https://codepen.io/joeylane/pen/dmGpdq
最满意答案
只需迭代div中的跨度并使用$(this)。()来获取每个数据的属性。
$("#trigger").click(function(){ $("#strength span").each(function(){ var strength = $(this).attr('data-strength'); console.log(strength); }) });<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <button id="trigger">Click Me</button> <div id="strength"> <span data-strength="60"></span> <span data-strength="50"></span> <span data-strength="40"></span> </div> </div>Just iterate ver the spans within the div and use $(this).() to get the data attribue of each.
$("#trigger").click(function(){ $("#strength span").each(function(){ var strength = $(this).attr('data-strength'); console.log(strength); }) });<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <button id="trigger">Click Me</button> <div id="strength"> <span data-strength="60"></span> <span data-strength="50"></span> <span data-strength="40"></span> </div> </div>
更多推荐
发布评论