我正在尝试在Jquery中编写代码来查找ul元素中的每个图像,并在我的html中在元素跨度之前添加它。非常感谢你。
JQuery的:
if($('#mod-links li img').length > 0){
$('#mod-link li img').each(function(){
alert('testing'); // just for test alert doesn't work in my case.
$(this).prependTo($(this).parent().closest('span));
});
}
HTML:
<ul id="mod-links">
<li style="padding-bottom: 10px;">
<img alt="test" src="borgwarner80.jpg " /><!-- this is image i need move before text in span -->
<a class="ui-link" href="?do=article">
<b>BorgWarner Chooses ATS ...eness (OEE) Deployments</b>
</a>
<br>
<span class="small">OEE is way to measure m...ality and productivity.</span><!-- this is is place where i need to prepend my image -->
<br class="clear">
</li>
<li style="padding-bottom: 10px;"></li><!-- same structure with different image and text -->
</ul>
答案 0 :(得分:2)
您需要选择正确的ID #mod-links
if($('#mod-links li img').length > 0){
$('#mod-links li img').each(function(){
// ^^^^
alert('testing'); // just for test alert doesn't work in my case.
$(this).prependTo($(this).parent().find('span'));
// ^^.find() ^^quote
});
}
您也可以像这样简化代码
$('#mod-links span.small').prepend(function(){
return $(this).closest('li').find('img');
});
答案 1 :(得分:0)
像这样使用,
$('#mod-link li img').each(function () {
$(this).parent().find("span").before(this);
});
修改强>
就像@Anton说的那样,你在id选择器中也有一个拼写错误,将#mod-link
更改为#mod-links
$('#mod-links li img').each(function () {
$(this).parent().find("span").before(this);
});
答案 2 :(得分:0)
您可以使用 .insertBefore() :
来缩短代码$('#mod-links img').each(function () {
$(this).insertBefore($(this).siblings('.small'));
});
<强> Fiddle Demo 强>
答案 3 :(得分:0)
在跨越兄弟之前移动它!
$('#mod-links li img').each(function(){
$(this).siblings('span').before(this);
});