I am trying to get the number inside of a <开发者_如何学Cspan>
I am using .each()
to find all the span
s but having problems getting the number inside of it. I would like to attach the number in the span to the image name, but no luck??
Code:
var _td = $("td.tri-img span");
$.each(_td, function(i, val){
$(val).html();
console.log(val);
var _img = $('.wrap-graph.relative img');
var _img_src = 'img/triangle' + val + '.png';
_img.attr('src', _img_src);
});
HTML:
<td class="tri-img"><img class="one"src="" alt="" ><span>11</span></td>
<td class="tri-img"><img class="two" src="" alt="" ><span>33</span></td>
<td class="tri-img"><img class="three" src="" alt="" ><span>44</span></td>
<td class="tri-img"><img class="four" src="" alt="" ><span>66</span></td>
Change
var _img_src = 'img/triangle' + val + '.png';
to
var _img_src = 'img/triangle' + val.innerHTML + '.png';
Try this:
$("td.tri-img span").each(function(){
var $this = $(this);
$this.prev('img').attr('src', 'img/triangle'+$this.text()+'.png');
});
EDIT: If you want to clean the text of any non-digits, do this:
$("td.tri-img span").each(function(){
var $this = $(this),
text = $this.text().replace(/\D/, '');
$this.prev('img').attr('src', 'img/triangle'+text+'.png');
});
精彩评论