2017-09-05 45 views
0
$('body').on('click', function() { 
    $('.detailTextContainer a').each(function() { 
    var urlFoto = $(this).attr('href'); 
    var imgElement = $("<img />").attr('src', urlFoto) 
           .addClass('dalsiFoto'); 

    $(this).empty().append(imgElement); 
    }); 
}); 

如何在加载页面(无事件)后自动运行此函数。 '.detailTextContainer a'是动态元素,它们在启动页面后立即加载到页面。jQuery动态元素自动运行的每种方法

我试过这段代码:

function showImage(){ 
    $('.detailFeatureDesc a').each(function() { 
    var urlFoto = $(this).attr('href'); 
    var imgElement = $("<img />").attr('src', urlFoto) 
           .addClass('dalsiFoto'); 
    $(this).empty().append(imgElement); 
    }); 
}; 

showImage(); 

但是,这并没有成功。

感谢

+0

参见:http://api.jquery.com/on/ 和https://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements –

+0

@Kamil请分享您的HTML代码或锚定标记代码,它们是动态加载的。 – Shiladitya

回答

0

可以使用load功能:

$(window).load(function() { 

     // create detailTextContainer here 
     $('.detailTextContainer a').each(function() { 
      var urlFoto = $(this).attr('href'); 
      var imgElement = $("<img />").attr('src', urlFoto) 
              .addClass('dalsiFoto'); 

     $(this).empty().append(imgElement); 

     }); 

}); 

从技术文档,当页面完全加载包括图形,这将运行功能。

或者你可以使用:

$(document).ready(function() { 

}); 

或简写:

$(function() { 

}); 

这只会一旦网页文档对象模型(DOM)运行准备的JavaScript代码来执行。

+0

感谢您的回复。但是你的.load()(在我的页面)的解决方案和我的一样。图片元素在点击事件后追加。 这个解决方案也不起作用: '$ function(){('.detailTextContainer a').each(function(){ var urlFoto = $(this).attr('href'); 变种imgElement = $( “”).attr( 'SRC',urlFoto) .addClass( 'dalsiFoto'); $(本).empty()追加(imgElement); }); };' –

+0

这应该有效,但是你必须在每个函数之前创建动态元素。尝试在每个之前创建它们在windows加载函数(或文档准备好)之前。如果没有html代码很难提供工作示例。 – amicoderozer

0

,你只要简单地写在功能窗口加载功能

<script> 
$(document).ready(function() { 
    console.log("document loaded"); 
}); 

$(window).on("load", function() { 
    //write your code is given section 
}); 
</script> 
0

你可以试试 “的” 听众

$(document).on("click", ".detailTextContainer a", function() { 
    // your code 
});